给定一个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 |
|