asp新闻网站模板百度开户推广
一、思路
这个题目主要有两个问题,一是什么时候切换方向,二是如何切换方向
问题一:此步移动完后,判断下一个元素,如果大于等于边界值(从0开始)或者小于边界值时或者访问数组为真时
问题二:创建一个方向数组,通过行数和列数的加减来实现切换方向,然后通过%4来循环访问这个数组
二、记忆
1.二维矩阵的使用长度声明和直接用数值定义
int[][] check = new int[rows][columns]; int[][] nextdirections ={{0,1},{1,0},{0,-1},{-1,0}};
2.方向数组来确定移动方向的思路
3.预判定的思路
int nextrow = row + nextdirections[nextdirection][0]; int nextcolumn = column + nextdirections[nextdirection][1]; if(nextcolumn>=columns || nextcolumn<0 || nextrow<0 || nextrow>=rows || check[nextrow][nextcolumn] ==1 ){nextdirection = (nextdirection+1)%4; }
三、代码
public List<Integer> spiralOrder(int[][] matrix){ArrayList<Integer> order = new ArrayList<>();//异常条件处理if(matrix == null || matrix.length == 0 || matrix[0].length ==0) return order;int rows = matrix.length,columns = matrix[0].length;int[][] check = new int[rows][columns];int[][] nextdirections ={{0,1},{1,0},{0,-1},{-1,0}};int total = rows*columns;int row = 0,column = 0;int nextdirection = 0;for(int i = 0;i<total;i++){order.add(matrix[row][column]);check[row][column] = 1;//预判,确定移动方向int nextrow = row + nextdirections[nextdirection][0];int nextcolumn = column + nextdirections[nextdirection][1];if(nextcolumn>=columns || nextcolumn<0 || nextrow<0 || nextrow>=rows || check[nextrow][nextcolumn] ==1 ){nextdirection = (nextdirection+1)%4;}//移动row += nextdirections[nextdirection][0];column += nextdirections[nextdirection][1];}return order;}