[算法][LeetCode]Spiral Matrix
生活随笔
收集整理的這篇文章主要介紹了
[算法][LeetCode]Spiral Matrix
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目要求
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:
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--3. 從右到左,y=yMax,x: xMax->xMin,yMax-- 4. 從下到上,x=xMin,y: yMax->uMin,xMin++ 結束條件,xMin==xMax或者yMin==yMax
還要要注意的地方:空數組的情況要處理。
Java代碼
public static ArrayList<Integer> spiralOrder(int[][] matrix) {ArrayList<Integer> order = new ArrayList<Integer>(); if (matrix.length == 0 || matrix[0].length == 0) return order;int xMin = 0;int yMin = 0;int xMax = matrix[0].length - 1;int yMax = matrix.length - 1;order.add(matrix[0][0]);int i = 0, j = 0;while (true) {while (i < xMax) order.add(matrix[j][++i]);if (++yMin > yMax) break;while (j < yMax) order.add(matrix[++j][i]);if (xMin > --xMax) break;while (i > xMin) order.add(matrix[j][--i]);if (yMin > --yMax) break;while (j > yMin) order.add(matrix[--j][i]);if (++xMin > xMax) break;}return order; }?
總結
以上是生活随笔為你收集整理的[算法][LeetCode]Spiral Matrix的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 腾讯云10亿扶持小程序:3元套餐可能免费
- 下一篇: C# Directory.Exists(