zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    3D 立体动态图 代码:
    自由切换 网页上的 ico 图标
    ES6 基本语法:
    JavaScript中class类的介绍
    React_01_ECMAScript6
    使用JS计算前一天和后一天
    Web 前端学习计划
    read
    java对象实例化
    关于为什么java需要垃圾回收
  • 原文地址:https://www.cnblogs.com/apanda009/p/7197016.html
Copyright © 2011-2022 走看看