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

    我们就用四个变量,向右移动增加colBegin,向下移动增加rowBegin,向左移动减小colEnd,向上移动减小rowEnd。
    当向左或向上移动时,必须检查行或列是否仍然存在,以防止重复

    class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res=new ArrayList<>();
            if(matrix==null||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){
                //向右遍历,遍历完rowBegin要加一,下移一行
                for(int j=colBegin;j<=colEnd;j++)
                    res.add(matrix[rowBegin][j]);
                rowBegin++;
                //向下遍历
                for(int i=rowBegin;i<=rowEnd;i++)
                    res.add(matrix[i][colEnd]);
                //左移一列,准备向左遍历
                colEnd--;
                //向左遍历之前要保证这一行是存在的(没有被遍历过)
                if(rowBegin<=rowEnd){
                    for(int j=colEnd;j>=colBegin;j--)
                        res.add(matrix[rowEnd][j]);
                }
                //上移一行
                rowEnd--;
                //向上遍历之前要保证这一列是存在的
                if(colBegin<=colEnd){
                    for(int i=rowEnd;i>=rowBegin;i--)
                        res.add(matrix[i][colBegin]);
                }
                //右移一列
                colBegin++;
            }
            return res;
        }
    }
  • 相关阅读:
    专业英语阅读(二)
    专业英语阅读(一)
    高精度运算
    高精度运算——加减乘除阶乘
    python常见编程面试题汇总
    python线程
    反射
    单例模式
    生成器、迭代器
    python装饰器
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8194278.html
Copyright © 2011-2022 走看看