题解 | #螺旋矩阵#
螺旋矩阵
https://www.nowcoder.com/practice/7edf70f2d29c4b599693dc3aaeea1d31
import java.util.ArrayList;
public class Solution {
public ArrayList<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(matrix.length==0) {
return res;
}
int i = 0, j = 0;
int[][] a = new int[matrix.length][matrix[0].length];
int count = 1;
int[][] direction = {
{0, 1},
{1, 0},
{0, -1},
{-1, 0}
};
int directionNumber = 0;
res.add(matrix[0][0]);
a[0][0] = 1;
while (count < (matrix.length * matrix[0].length)) {
i += direction[directionNumber % 4][0];
j += direction[directionNumber % 4][1];
if (i >= 0 && j >= 0 && i < matrix.length && j < matrix[0].length &&
a[i][j] != 1) {
res.add(matrix[i][j]);
a[i][j] = 1;
count++;
} else {
i -= direction[directionNumber % 4][0];
j -= direction[directionNumber % 4][1];
directionNumber++;
}
};
return res;
}
}