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 閱讀(693) 評論(0)  編輯  收藏 所屬分類: Leetcode
          主站蜘蛛池模板: 广饶县| 兰坪| 佛坪县| 扎兰屯市| 那坡县| 板桥市| 青龙| 诏安县| 惠来县| 平凉市| 北京市| 巴彦淖尔市| 赫章县| 桂林市| 乐山市| 黄梅县| 安远县| 静乐县| 宁夏| 鲜城| 海原县| 淮阳县| 锡林郭勒盟| 徐水县| 安多县| 临朐县| 崇礼县| 南江县| 柏乡县| 汕头市| 孟州市| 富宁县| 科技| 江西省| 株洲县| 加查县| 旬阳县| 西青区| 霍州市| 彩票| 佛学|