给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
示例 1:
输入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
输出: [1,2,3,6,9,8,7,4,5]
示例 2:
输入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
输出: [1,2,3,4,8,12,11,10,9,5,6,7]
思路
看准每一圈的起点,第一圈起点为(0,0),下一圈起点为(1,1),以此类推
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> list = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0) {
return list;
}
boolean[][] inq = new boolean[matrix.length][matrix[0].length];
for (int i = 0, j = 0; i < matrix.length && j < matrix[0].length; i++,j++) {
if (inq[i][j] == false) {
spiral(matrix, i, j, inq, list);
}else {
break;
}
}
return list;
}
public void spiral(int[][] matrix, int i, int j, boolean[][] inq, List<Integer> list) {
int r = 0, c = 0;
for (c = j; c < matrix[0].length; c++) {
if (inq[i][c] == false) {
list.add(matrix[i][c]);
inq[i][c] = true;
}else {
break;
}
}
c = c - 1;
for (r = i + 1; r < matrix.length; r++) {
if (inq[r][c] == false) {
list.add(matrix[r][c]);
inq[r][c] = true;
}else {
break;
}
}
r = r - 1;
for (c = c - 1; c >= 0; c--) {
if (inq[r][c] == false) {
list.add(matrix[r][c]);
inq[r][c] = true;
}else {
break;
}
}
c = c + 1;
for (r = r - 1; r >= 0; r--) {
if (inq[r][c] == false) {
list.add(matrix[r][c]);
inq[r][c] = true;
}else {
break;
}
}
}
}
网友评论