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


  • 相关阅读:
    HDU1814 Peaceful Commission
    POJ1679 The Unique MST
    POJ 3243 Clever Y
    POJ 3463 Sightseeing
    POJ1274 The Perfect Stall
    POJ 2417 Discrete Logging
    POJ1011 Sticks
    前端面试资源整理(一)
    小程序和腾讯地图联合使用
    快速创建 HTML5 Canvas 电信网络拓扑图
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5041607.html
Copyright © 2011-2022 走看看