模拟
第一列是行的变化,第二列是列的变化
{0, 1},上
{1, 0}, 右
{0, -1}, 下
{-1, 0},左
简洁代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result =new ArrayList<>();
int rows=matrix.length;
int cols=matrix[0].length;
int total=rows*cols;
//建立辅助数组,访问数组visited,方向数组direction
boolean[][] visited=new boolean[rows][cols];
int[][] direction={{0,1},{1,0},{0,-1},{-1,0}};
//建立辅助变量
int directIndex=0;
int row=0;
int col=0;
//遍历所有数据
for(int i=0;i<total;i++){
//先把matrix[row][col]加入
result.add(matrix[row][col]);
visited[row][col]=true;
//判断是否需要改变方向,即directIndex
int nextRow=row+direction[directIndex][0];
int nextCol=col+direction[directIndex][1];
if(nextCol<0||nextRow<0||nextCol>=cols||nextRow>=rows||visited[nextRow][nextCol]==true){
directIndex=(directIndex+1)%4;
}
//更新row和col
row=row+direction[directIndex][0];
col=col+direction[directIndex][1];
}
return result;
}
}
详细代码
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return order;
}
int rows = matrix.length, columns = matrix[0].length;
boolean[][] visited = new boolean[rows][columns];
int total = rows * columns;
int row = 0, column = 0;
// 存储下一个索引变化+1-1or不变 row += directions[1][0]
//分别是一圈 右走的时候(row不变 col+1)下走 左走 上走
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
//刚开始先右走 因此directionIndex = 0 direction[0][0/1]
int directionIndex = 0;
//遍历完所有的元素,截止
for (int i = 0; i < total; i++) {
//加入当前元素
order.add(matrix[row][column]);
//访问为设为true
visited[row][column] = true;
//判断是否需要更新direction
//即判断加上当前的directions[][]数组的值之后 行列的索引是否超过了4或0
int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1];
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) {
//超过则换方向 比如刚开始是走到了最右侧,加上之后nextcol>4
//因此direction改为第二个[1][0]
directionIndex = (directionIndex + 1) % 4;
}
//通过direction走
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
}
按层模拟
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return order;
}
int rows = matrix.length, columns = matrix[0].length;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
order.add(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
order.add(matrix[row][right]);
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
order.add(matrix[bottom][column]);
}
for (int row = bottom; row > top; row--) {
order.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
}