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].

    此题关键点在于开始要设置四个边节点,在设置一个遍历变量(分别依次代表col,row,col,row)。接下来出界条件是begin>end值,然后每次遍历一行或一列的时候,把那一行或那一列的边界值去掉,代码如下:

    public class Solution {

        public List<Integer> spiralOrder(int[][] matrix) {

            List<Integer> res = new ArrayList<Integer>();

            if(matrix==null||matrix.length==0||matrix[0].length==0) return res;

            int rowbegin = 0;

            int rowend = matrix.length-1;

            int colbegin = 0;

            int colend = matrix[0].length-1;

            while(true){

                for(int i=colbegin;i<=colend;i++){

                    res.add(matrix[rowbegin][i]);

                }

                rowbegin++;

                if(rowbegin>rowend) break;

                for(int i=rowbegin;i<=rowend;i++){

                    res.add(matrix[i][colend]);

                }

                colend--;

                if(colbegin>colend) break;

                for(int i=colend;i>=colbegin;i--){

                    res.add(matrix[rowend][i]);

                }

                rowend--;

                if(rowbegin>rowend) break;

                for(int i=rowend;i>=rowbegin;i--){

                    res.add(matrix[i][colbegin]);

                }

                colbegin++;

                if(colbegin>colend) break;

            }

            return res;

        }

    }

  • 相关阅读:
    jvm的内部体系结构浅析--转
    完整java开发中JDBC连接数据库代码和步骤--转
    java语言的线程安全级别--转
    java 中hashcode 与 equals的关系
    mysql 错误 SQL Error: 1366: Incorrect string value: "xE8xAFxA6xE7xBBx86…" for column "address" a
    Linux查看CPU和内存使用情况
    5.2、访问限制
    5、面向对象编程(5.1、类和实例)
    4.5、偏函数
    4.4、装饰器
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6363918.html
Copyright © 2011-2022 走看看