您的位置:首页 > 其它

59. Spiral Matrix II && 54. Spiral Matrix

2017-09-18 21:59 393 查看
Given an integer n, generate a square matrix filled with elements from 1 ton2 in spiral order.For example,Given n =
3
,You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
这道题目比较有意思 但似乎一开始没什么思路。于是参考的discussion:螺旋形加入数值可以看作一种循环,每个循环里面在四个方向上加入数值,用四个参数来保存上下左右的边界,最后上下边界相等时循环结束。在循环内,每次结束一个方向的赋值就有一个边界的大小发生变化。
class Solution {
public int[][] generateMatrix(int n) {
int top=0,left=0;
int bottom=n-1,right=n-1;
int[][] res = new int

;
int count=1;
while(left<=right){
for(int i=left;i<=right;i++)
res[top][i] = count++;
top++;
for(int i=top;i<=bottom;i++)
res[i][right] = count++;
right--;
for(int i=right;i>=left;i--)
res[bottom][i]=count++;
bottom--;
for(int i=bottom;i>=top;i--)
res[i][left]=count++;
left++;
}
return res;
}
}
54. Spiral Matrix                   Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.For example,Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return
[1,2,3,6,9,8,7,4,5]
.这两道题目区别主要在:上一道题目是方阵,所以右边界和下边界是一样的,不用分开判断,所以在while循环中这道题就要有有两个条件。那么代码就是:class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> res=new ArrayList<Integer>();int m = matrix.length;if(m==0)return res;int n = matrix[0].length;int left =0,top=0;int right=n-1,bottom=m-1;while(left<=right&&top<=bottom){for(int i=left;i<=right;i++)res.add(matrix[top][i]);top++;for(int i=top;i<=bottom;i++)res.add(matrix[i][right]);right--;for(int i=right;i>=left;i--)res.add(matrix[bottom][i]);bottom--;for(int i=bottom;i>=top;i--)res.add(matrix[i][left]);left++;}return res;}}但是考虑两种情况:[[7,9,6]]和[[7].[9],[6]].前者结果是[[7,9,6,9]],后者结果是[[7],[9],[6],[9]],多了一个数字,这是为什么呢?经过走一次全过程发现:在最后一个循环中后面两个for循环其实已经不能执行了,但是因为while已经判断过不能及时跳出循环。 因此,在后面两个for循环上还要加上一个判断:class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> res=new ArrayList<Integer>();int m = matrix.length;if(m==0)return res;int n = matrix[0].length;int left =0,top=0;int right=n-1,bottom=m-1;while(left<=right&&top<=bottom){for(int i=left;i<=right;i++)res.add(matrix[top][i]);top++;for(int i=top;i<=bottom;i++)res.add(matrix[i][right]);right--;if(top<=bottom&&left<=right){for(int i=right;i>=left;i--)res.add(matrix[bottom][i]);bottom--;for(int i=bottom;i>=top;i--)res.add(matrix[i][left]);left++;}}return res;}}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  array