給定一個m*n的矩陣,輸入全部元素的螺旋順序。java
使用計算輸出的方法,先處理上面一行,再處理右邊一列,再處理下面一行,再處理左邊一列,一直這樣操做,直到全部的元素都處理完。算法
算法實現類shell
import java.util.ArrayList; import java.util.List; public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> result = new ArrayList<>(50); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return result; } // 只有一行的狀況 if (matrix.length == 1) { for (int i : matrix[0]) { result.add(i); } return result; } // 只有一列的狀況 if (matrix[0].length == 1) { for (int i = 0; i < matrix.length; i++) { result.add(matrix[i][0]); } return result; } // 計算有多少圈 int row = matrix.length; int col = matrix[0].length; int cycle = row < col ? row : col; cycle = (cycle + 1) / 2; int round = 0; // 記錄當前是第幾圈 int left = 0; int right = matrix[0].length - 1; int top = 0; int down = matrix.length - 1; int total = col*row; int count = 0; while (round < cycle) { // 上面一行 for (int i = left; i <= right && count < total; i++) { count++; result.add(matrix[round][i]); } top++; // // 右邊一列 for (int i = top; i <= down && count < total; i++) { count++; result.add(matrix[i][col - round - 1]); } right--; // 底下一行 for (int i = right; i >= left && count < total; i--) { count++; result.add(matrix[row - round - 1][i]); } down--; // 左邊一列 for (int i = down; i >= top && count < total; i--) { count++; result.add(matrix[i][round]); } left++; round++; } return result; } }
螺旋矩陣是指一個呈螺旋狀的矩陣,它的數字由第一行開始到右邊不斷變大,向下變大,
向左變大,向上變大,如此循環。ide
1this 2spa 3.net 4code 5ci 6get 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
|