您的位置:首页 > 其它

leetcode 54 54. Spiral Matrix(矩阵顺时针绕圈输出)

2017-01-02 09:21 429 查看
思路:

我是开辟了一个和原矩阵同样大小的矩阵temp来存放是否输出过的标志位,然后按照向右,向左,向上,向下的顺时针顺序来挨个输出,虽然空间复杂度大了一点,但是好处是思路比较简单,不容易错误。

据说《剑指offer》上有这道题或者类似的题,带我看了剑指offer回来补充补充。

import java.util.ArrayList;
import java.util.List;

public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
int i,j; //i为行数,j为列数
int count=0;

// result.add(new Integer(matrix[0][0]));
if(matrix.length == 0)
return result;
int [][]temp = new int[matrix.length][];
for(i=0;i<matrix.length;i++)
temp[i] = new int[matrix[i].length];

int row = temp.length;
for(i=0;i<row;i++)
for(j=0;j<temp[i].length;j++)
temp[i][j] = 0;

i=j=0;
//int flag = 1; //第一个数
result.add(new Integer(matrix[0][0]));
temp[0][0] = 1;
while(true)
{
while(j+1<temp[i].length && temp[i][j+1] == 0)
{ //向右
j++;
temp[i][j] = 1;
result.add(new Integer(matrix[i][j]));
}

while(i+1 < temp.length && temp[i+1][j] == 0)
{//向下
i++;
temp[i][j] = 1;
result.add(new Integer(matrix[i][j]));
}

while(j-1 >= 0 && temp[i][j-1] == 0)
{//向左
j--;
temp[i][j] = 1;
result.add(new Integer(matrix[i][j]));
}

while(i-1 >= 0 && temp[i-1][j] == 0)
{//向上
i--;
temp[i][j] = 1;
result.add(new Integer(matrix[i][j]));
}

if((j+1==temp[i].length || temp[i][j+1] != 0) && (i+1 == temp.length || temp[i+1][j] != 0) && (j-1 < 0 || temp[i][j-1] != 0) && (i-1 < 0 || temp[i-1][j] != 0))
break;
}
return result;
}

public static void main(String args[])
{
int i;
//int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
List<Integer> result;
result = new Solution().spiralOrder(matrix);
for(i=0;i<result.size();i++)
{
System.out.print(result.get(i)+"__");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: