政府網(wǎng)站欄目設(shè)計原則/網(wǎng)絡(luò)軟文
一、思路
這個題目主要有兩個問題,一是什么時候切換方向,二是如何切換方向
問題一:此步移動完后,判斷下一個元素,如果大于等于邊界值(從0開始)或者小于邊界值時或者訪問數(shù)組為真時
問題二:創(chuàng)建一個方向數(shù)組,通過行數(shù)和列數(shù)的加減來實現(xiàn)切換方向,然后通過%4來循環(huán)訪問這個數(shù)組
二、記憶
1.二維矩陣的使用長度聲明和直接用數(shù)值定義
int[][] check = new int[rows][columns]; int[][] nextdirections ={{0,1},{1,0},{0,-1},{-1,0}};
2.方向數(shù)組來確定移動方向的思路
3.預(yù)判定的思路
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;//預(yù)判,確定移動方向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;}