• Leetcode: Spiral Matrix. Java


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


    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> res = new ArrayList<Integer>();
            int m = matrix.length;
            if(m == 0) return res;
            int n = matrix[0].length;
            //循环次数小于m/2和n/2
            for(int i = 0; i < m/2 && i < n/2; i++){
                for(int j = 0; j < n - 1 - i * 2; j++)
                    res.add(matrix[i][i+j]);
                for(int j = 0; j < m - 1 - i * 2; j++)
                    res.add(matrix[i+j][n-i-1]);
                for(int j = 0; j < n - 1 - i * 2; j++)
                    res.add(matrix[m-i-1][n-i-1-j]);
                for(int j = 0; j < m - 1 - i * 2; j++)
                    res.add(matrix[m-i-1-j][i]);
            }
            //循环结束后假设行数/列数是奇数,则还剩一行/列
            if(m % 2 != 0 && m <= n){
                for(int j = 0; j < n - (m/2) * 2; j++)
                    res.add(matrix[m/2][m/2+j]);  
            }
            else if(n % 2 != 0 && m > n){
                for(int j = 0; j < m - (n/2) * 2; j++)
                     res.add(matrix[n/2+j][n/2]);
            }
            return res;
        }
    }


  • 相关阅读:
    VS2013
    有了门面,程序会更加体面!- pos软件基于三层架构 -09
    无熟人难办事?- 闲聊设计模式-迪米特法则
    三层架构,分层开发
    Filezilla 错误
    归档和压缩
    在Linux系统下用dd命令制作ISO镜像U盘启动盘
    脚本语言
    node.js知识点提取
    npm cnpm
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5041607.html
Copyright © 2020-2023  润新知