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].
tag: 摩根斯丹利 技术研发部 笔试原题
思路: 看到矩阵型题目,首先想到的是坐标转换, 找到坐标转换规律。
本题 按照一圈圈思路从外到内逐步遍历。 边界容易出错。
上右下左:
matrix[x][y + i]
matrix[x + j][y + cols - 1]
matrix[x + rows - 1][y + i]
matrix[x + i ][y]
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
if(matrix == null || matrix.length == 0) {
return result;
}
int rows = matrix.length;
int cols = matrix[0].length;
int x = 0;
int y = 0;
visitSpiral(matrix, x, y, rows, cols, result);
return result;
}
public void visitSpiral(int[][] matrix, int x, int y, int rows, int cols, List<Integer> result) {
if(rows <= 0 || cols <= 0) {
return;
}
// first line
for(int i = 0; i < cols; i++) {
result.add(matrix[x][y + i]);
}
// right column
for(int j = 1; j < rows - 1; j++) {
result.add(matrix[x + j][y + cols - 1]);
}
if(rows > 1) {
for(int i = cols - 1; i >= 0; i--) {
result.add(matrix[x + rows - 1][y + i]);
}
}
if(cols > 1) {
for(int i = rows - 2; i > 0; i--) {
result.add(matrix[x + i ][y]);
}
}
visitSpiral(matrix,x + 1, y + 1, rows - 2, cols - 2,result);
}
}