54. 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:

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

难度:87,这道题跟 Rotate Image 很相似,都是需要把矩阵分割成层来处理,每一层都是按:1. 正上方;2. 正右方;3. 正下方;4. 正左方这种顺序添加元素到结果集合。实现中要注意细节,when I traverse left or up I have to check whether the row or col still exists to prevent duplicates.

public class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        
        List<Integer> res = new ArrayList<Integer>();
        
        if (matrix.length == 0) {
            return res;
        }
        
        int rowBegin = 0;
        int rowEnd = matrix.length-1;
        int colBegin = 0;
        int colEnd = matrix[0].length - 1;
        
        while (rowBegin <= rowEnd && colBegin <= colEnd) {
            // Traverse Right
            for (int j = colBegin; j <= colEnd; j ++) {
                res.add(matrix[rowBegin][j]);
            }
            rowBegin++;
            
            // Traverse Down
            for (int j = rowBegin; j <= rowEnd; j ++) {
                res.add(matrix[j][colEnd]);
            }
            colEnd--;
            
            if (rowBegin <= rowEnd) {
                // Traverse Left
                for (int j = colEnd; j >= colBegin; j --) {
                    res.add(matrix[rowEnd][j]);
                }
            }
            rowEnd--;
            
            if (colBegin <= colEnd) {
                // Traver Up
                for (int j = rowEnd; j >= rowBegin; j --) {
                    res.add(matrix[j][colBegin]);
                }
            }
            colBegin ++;
        }
        
        return res;
    }
}

  

 矩阵非图的题就得找规律, 自己在一遍遍的走, 然后看看遍历顺序和开始行结束行, 开始列结束列的关系, 自己找一找corner case, 看看是否有越界问题.

然后就是得分情况讨论, 记住coner case

posted @ 2017-07-17 18:50  apanda009  阅读(103)  评论(0编辑  收藏  举报