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

  • 相关阅读:
    获得音视频信息
    stf-多设备管理平台搭建
    接口用例设计
    阿里云Ubuntu服务器搭建SVN
    Jenkins首次启动卡在加载页面
    初使Jenkins构建Python项目
    MongoDB使用python脚本写入数据
    python re操作
    使用Python脚本写入MongoDB数据
    chromedriver与chrome版本对应表及下载地址
  • 原文地址:https://www.cnblogs.com/apanda009/p/7197016.html
Copyright © 2011-2022 走看看