package 剑指offer.数组;
import java.util.ArrayList;
import java.util.List;
/**
*
* 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
* 1 2 3
* 4 5 6
* 7 8 9
* 输出:[1,2,3,6,9,8,7,4,5]
* 坐标变化:(0,0)(0,1)(0,2) 拐弯(1,2)(2,2)拐弯(2,1)(2,0)拐弯(1,0) 拐弯(1,1)
*
*
*/
public class leetcode54螺旋矩阵 {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> order = new ArrayList<Integer>();
//null矩阵 只有一行 或者一列 不行
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return order;
}
//获取行列
int rows = matrix.length, columns = matrix[0].length;
//构造是否访问过的visited矩阵
boolean[][] visited = new boolean[rows][columns];
//元素个数
int total = rows * columns;
//初始化row column
int row = 0, column = 0;
//对数组进行访问时的方向
int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
int directionIndex = 0;
/**
* 行变化 列变化
* 0 1 (右走)
* 1 0 (下走)
* 0 -1 (左走)
* -1 0 (上走)
*
*/
for (int i = 0; i < total; i++) {
//加入order数组
order.add(matrix[row][column]);
//visited矩阵
visited[row][column] = true;
//定义nextrow nextcolumn下一次要走的方向 判断是否拐弯
int nextRow = row + directions[directionIndex][0];
int nextColumn = column + directions[directionIndex][1];
//当发生发生转弯的时候 有五种情况:
//右侧碰到边界(nextColumn>=columns);左侧碰到边界(nextColumn < 0)
//下侧碰到边界(nextRow >= rows);上侧碰到边界(nextRow < 0)
//以及马上访问到已经访问过的元素
if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns
|| visited[nextRow][nextColumn]) {
//2%4=2 4%4=0
//开始转向
directionIndex = (directionIndex + 1) % 4;
}
row += directions[directionIndex][0];
column += directions[directionIndex][1];
}
return order;
}
}
leetcode54螺旋矩阵
最新推荐文章于 2024-03-12 13:44:10 发布