Spiral Matrix 解答

时间:2023-03-08 21:05:56
Spiral Matrix 解答

Question

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].

Solution

这道题只有笨方法,就是老老实实地遍历输入的二维数组,得到结果。

但是在遍历时有个技巧,就是按照环来遍历。(x, y)为遍历点的坐标。我们发现,当遍历完一圈后,(x, y)又会回到起点。所以对于接下来里面一圈的遍历,只需x++, y++即可。

Spiral Matrix 解答

由于输入不一定是正方形,有可能最后剩的一圈是一行或一列,此时根据省下的行数/列数判断,另行处理。

 public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<Integer>();
if (matrix == null || matrix.length < 1)
return result;
int m = matrix.length, n = matrix[0].length, x = 0, y = 0;
while (m > 0 && n > 0) {
// If only one row left
if (m == 1) {
for (int i = 0; i < n; i++)
result.add(matrix[x][y++]);
break;
}
// If only one column left
if (n == 1) {
for (int i = 0; i < m; i++)
result.add(matrix[x++][y]);
break;
}
// Otherwise, we traverse in a circle
// Left to Right
for (int i = 0; i < n - 1; i++)
result.add(matrix[x][y++]);
// Up to Down
for (int i = 0; i < m - 1; i++)
result.add(matrix[x++][y]);
// Right to Left
for (int i = 0; i < n - 1; i++)
result.add(matrix[x][y--]);
// Down to Up
for (int i = 0; i < m - 1; i++)
result.add(matrix[x--][y]);
x++;
y++;
m -= 2;
n -= 2;
}
return result;
}
}