由題目咱們能夠發現規律,就是一圈一圈往裏走,那麼每一圈都是以左上角[0,0]爲頂點開始走,而後走一圈到左上角下面那個點就走完了,而後開始下一圈就是[1,1],而後開始新的一圈
數組
class Solution { public int[] spiralOrder(int[][] matrix) { //首先判斷矩陣不爲空 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return new int[0]; } //矩陣不爲空,就先定義一個和他長度同樣的數組 int i_len = matrix.length; int j_len = matrix[0].length; int[] array= new int[i_len*j_len]; int index = 0;//定義新的一維數組的索引點 //找規律 要先定義上下左右邊界 不可以超出 int top = 0;int down = i_len-1; int left = 0;int right = j_len-1; //定義最後返回的條件走完全部圈以後 兩個邊界能夠重,但不能小,由於小了就說明已經錯行了 while(left<=right&&top<=down){ //上面的行索引完畢 for(int i = left;i<=right;i++){ array[index++] = matrix[top][i]; } //右側列索引 上面那個for已經包括了右上角那個點 for(int j = top+1;j<=down;j++){ array[index++] = matrix[j][right]; } //下面的行索引 上面那個for已經包括了右下角的點 //判斷條件不能等於,若是等於當列比行多的時候就會走這個循環多加值了 //就是下來走的行仍是前面的相同那行 //因此要判斷此時的right和left top down //若是有兩個值是相同的那說明就生下了一行或者一列 在上面的行和列就已經走完了 //若是兩個值都不相等也不大於,那就說明還有圈 繼續走 if(left<right&&top<down){ for(int k = right-1;k>left;k--){ array[index++] = matrix[down][k]; } //左側列索引 for(int m = down;m>top;m--){ array[index++] = matrix[m][left]; } } left++; top++; right--; down--; } return array; } }
注意
//下面的行索引 上面那個for已經包括了右下角的點
//判斷條件不能等於,若是等於當列比行多的時候就會走這個循環多加值了
//就是下來走的行仍是前面的相同那行
//因此要判斷此時的right和left top down
//若是有兩個值是相同的那說明就生下了一行或者一列 在上面的行和列就已經走完了
//若是兩個值都不相等也不大於,那就說明還有圈 繼續走
spa
class Solution { public int[] spiralOrder(int[][] matrix) { //判斷輸入的矩陣不爲空 if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return new int[0]; } int rows = matrix.length, columns = matrix[0].length; //定義一個輔助矩陣,表徵是否訪問過此位置的元素 默認值是false boolean[][] visited = new boolean[rows][columns]; int total = rows * columns; int[] order = new int[total]; int row = 0, column = 0; //定義四個方向數組,不一樣方向到時候選不一樣的數組 //當前行列分別加0,1就是往右走 //當前行列分別加1,0就是往下走 //當前行列分別加0,-1就是往左走 //當前行列分別加-1,0就是往上走 int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int directionIndex = 0; for (int i = 0; i < total; i++) { //當前點的值加入新矩陣 order[i] = matrix[row][column]; //訪問過當前點 當前點位置在輔助矩陣置爲true visited[row][column] = true; //下一個點的座標 int nextRow = row + directions[directionIndex][0], nextColumn = column + directions[directionIndex][1]; //判斷下一個點是否是越界或者已經訪問過 //下一個索引點本應該到達拐點的下一個點(角頂點的下一個)的時候,發現上面那個nextrow仍是在原來的基礎上再同一方向走了一個點,走完以後就超出索引了,因此此時就應該拐彎了,而後根據directionIndex+1.來走下一方向,若是此時directionIndex=3,再+1,後面就directionIndex變成0,就說明前面一圈走完了,就進入下一圈 //或者下一個點已經訪問過了那就換方向,若是上下左右四個方向都訪問過了,那就說明是最後一個點,就結束了 if (nextRow < 0 || nextRow >= rows || nextColumn < 0 || nextColumn >= columns || visited[nextRow][nextColumn]) { directionIndex = (directionIndex + 1) % 4; } //判斷沒有不知足題目,就找到下一個真的索引 row += directions[directionIndex][0]; column += directions[directionIndex][1]; } return order; } }
這個邏輯思惟厲害了
code