[leetcode] 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].
https://oj.leetcode.com/problems/spiral-matrix/
思路:这题目不难理解,就是注意边界情况, 推荐用 上下左右4个bar的方法,简单不易出错。
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if (matrix == null || matrix.length < 1 || matrix[0].length < 1)
return res;
int left = 0;
int right = matrix[0].length - 1;
int top = 0;
int bottom = matrix.length - 1;
while (left <= right && top <= bottom) {
int i;
for (i = left; i <= right; i++)
res.add(matrix[top][i]);
for (i = top + 1; i <= bottom; i++)
res.add(matrix[i][right]);
if (top < bottom)//corner case, no need back to left if top==bottom
for (i = right - 1; i >= left; i--)
res.add(matrix[bottom][i]);
if (left < right)//corner case, no need back up if left==right
for (i = bottom - 1; i >= top + 1; i--)
res.add(matrix[i][left]);
top++;
bottom--;
left++;
right--;
}
return res;
}
public static void main(String[] args) {
int[][] matrix = new int[][] { { 1,2 }, { 5,6 }, { 9,10 } };
System.out.println(new Solution().spiralOrder(matrix));
}
}
第二遍记录:行和列可能不同,所以需要4个指针指明界限。
遍历时,1.先横向(一定要包含right),2.再纵向向下(一定要包含bottom),3.再从右向左(如果需要),4.再从下到上(如果需要)。
上面一定能够要包含right和bottom的原因是,考虑只有一行或者一列的特殊情况,3和4不输出,所以1和2此时一定要尽可能输出所有的元素。

浙公网安备 33010602011771号