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]

    程序

    public class Solution {
        public List<Integer> spiralOrder(int[][] matrix) {
            List<Integer> path = new ArrayList<Integer>();
            if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
                return path;
            }
            
            int i = 0, j = 0;
            int n = matrix.length, m = matrix[0].length;
            int cnt = n * m;
            int cyc = 0;
            
            while (true) {
                // to right
                while (j < m - cyc) {
                    path.add(matrix[i][j++]);
                }
                --j;
                ++i;
                // to bottom
                while (i < n - cyc) {
                    path.add(matrix[i++][j]);
                }
                --i;
                --j;
                if (path.size() == cnt) {
                    break;
                }
                
                // to left
                while (j >= cyc) {
                    path.add(matrix[i][j--]);
                }
                ++j;
                --i;
                // to top
                while (i > cyc) {
                    path.add(matrix[i--][j]);
                }
                ++i;
                ++j;
                if (path.size() == cnt) {
                    break;
                }
                
                ++cyc;
            }
            
            return path;
        }
    }
    

      

  • 相关阅读:
    Redis_配置文件
    Redis_数据使用
    QQ登录测试用例
    JMeter性能测试入门--偏重工具的使用
    浅说《测试用例》
    axure界面功能
    性能测试相关术语
    测试用例设计和测试环境搭建
    测试需求分析
    软件测试的过程
  • 原文地址:https://www.cnblogs.com/harrygogo/p/4672549.html
Copyright © 2011-2022 走看看