IT技術小屋

          秋風秋雨,皆入我心

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            38 隨筆 :: 1 文章 :: 19 評論 :: 0 Trackbacks
          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, 3 ],
           [ 4, 5, 6 ],
           [ 7, 8, 9 ]
          ]
          You should return [1,2,3,6,9,8,7,4,5].

          可以為矩陣設置上下左右四個邊界,每次繞著這四個邊界打印元素。實現代碼如下:
           1 public class Solution {
           2     public ArrayList<Integer> spiralOrder(int[][] matrix) {
           3         ArrayList<Integer> ret = new ArrayList<Integer>();
           4         if (matrix.length == 0) return ret;
           5         int upper = 0, bottom = matrix.length - 1;
           6         int left = 0, right = matrix[0].length - 1;
           7         int i = 0, j = 0;
           8         while (true) {
           9             for (i = left; i <= right; i++) {
          10                 ret.add(matrix[upper][i]);
          11             }
          12             if (++upper > bottom) break;
          13             for (j = upper; j <= bottom; j++) {
          14                 ret.add(matrix[j][right]);
          15             }
          16             if (--right < left) break;
          17             for (i = right; i >= left; i--) {
          18                 ret.add(matrix[bottom][i]);
          19             }
          20             if (--bottom < upper) break;
          21             for (j = bottom; j >= upper; j--) {
          22                 ret.add(matrix[j][left]);
          23             }
          24             if (++left > right) break;
          25         }
          26         return ret;
          27     }
          28 }
          posted on 2013-12-22 16:59 Meng Lee 閱讀(692) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 定结县| 彝良县| 安达市| 沙坪坝区| 调兵山市| 拉萨市| 天气| 浙江省| 泸水县| 六盘水市| 安图县| 福清市| 仙游县| 友谊县| 朔州市| 西吉县| 临桂县| 中牟县| 招远市| 新余市| 乳山市| 邯郸县| 屯昌县| 新民市| 吴堡县| 金溪县| 康马县| 常熟市| 尼木县| 克东县| 鲁甸县| 翁牛特旗| 娱乐| 金山区| 鄢陵县| 南丹县| 金华市| 睢宁县| 合肥市| 肇东市| 永年县|