54. Spiral Matrix
作者:互联网
This is an exactly same problem with "59. Spiral Matrix II". I set every direction as a status, when one direction was implemented, the current status turns to the next status.
Which different status, the scan direction is different, but all scans cannot exceed the edges of the matrix.
The time complexity is O(m*n):
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> res = new ArrayList<>(); if (matrix == null || matrix.length == 0 || matrix[0].length == 0) return res; int m = matrix.length; int n = matrix[0].length; int top = 0, bottom = m - 1, left = 0, right = n - 1; int status = 0; //we set every directions as a status, there are toally 4 status. while (top <= bottom && left <= right) { if (status % 4 == 0) { //the first direction, from left to right for (int j = left; j <= right; j++) { res.add(matrix[top][j]); } top++; } else if (status % 4 == 1) { //the second direction, from top to bottom for (int i = top; i <= bottom; i++) { res.add(matrix[i][right]); } right--; } else if (status % 4 == 2) { //the third direction, from right to left for (int j = right; j >= left; j--) { res.add(matrix[bottom][j]); } bottom--; } else if (status % 4 == 3) { //the fourth direction, from bottom to top for (int i = bottom; i >= top; i--) { res.add(matrix[i][left]); } left++; } } return res; }
标签:status,matrix,bottom,int,54,top,Spiral,res,Matrix 来源: https://www.cnblogs.com/feiflytech/p/15862380.html