[算法][LeetCode]Spiral Matrix

﹏ヽ暗。殇╰゛Y 2021-12-13 22:33 240阅读 0赞

题目要求

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

  1. [
  2. [ 1, 2, 3 ],
  3. [ 4, 5, 6 ],
  4. [ 7, 8, 9 ]
  5. ]

You should return [1,2,3,6,9,8,7,4,5].

分析

举个例子自己从头到尾把数字列出来,很容易就找到规律了:

假设一维数组的坐标为x,取值范围是xMin~xMax;二维数组的坐标为y,取值范围是yMin~yMax。(也就是数组表示为int[y][x])

  1. 从左到右,y=yMin,x: xMin->xMax,yMin++

  2. 从上到下,x=xMax,y: yMin->yMax,xMax—

  1. 从右到左,y=yMax,x: xMax->xMin,yMax—

  2. 从下到上,x=xMin,y: yMax->uMin,xMin++

结束条件,xMin==xMax或者yMin==yMax

还要要注意的地方:空数组的情况要处理。

Java代码

  1. public static ArrayList<Integer> spiralOrder(int[][] matrix) {
  2. ArrayList<Integer> order = new ArrayList<Integer>();
  3. if (matrix.length == 0 || matrix[0].length == 0) return order;
  4. int xMin = 0;
  5. int yMin = 0;
  6. int xMax = matrix[0].length - 1;
  7. int yMax = matrix.length - 1;
  8. order.add(matrix[0][0]);
  9. int i = 0, j = 0;
  10. while (true) {
  11. while (i < xMax) order.add(matrix[j][++i]);
  12. if (++yMin > yMax) break;
  13. while (j < yMax) order.add(matrix[++j][i]);
  14. if (xMin > --xMax) break;
  15. while (i > xMin) order.add(matrix[j][--i]);
  16. if (yMin > --yMax) break;
  17. while (j > yMin) order.add(matrix[--j][i]);
  18. if (++xMin > xMax) break;
  19. }
  20. return order;
  21. }

转载于:https://www.cnblogs.com/james1207/p/3400100.html

发表评论

表情:
评论列表 (有 0 条评论,240人围观)

还没有评论,来说两句吧...

相关阅读