zoukankan      html  css  js  c++  java
  • Leetcode 54. Spiral Matrix

    54. Spiral Matrix

    • Total Accepted: 66779
    • Total Submissions: 286442
    • Difficulty: Medium

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

    思路:模拟,一圈圈地环绕,直到停止。

    代码:

     1 class Solution {
     2 public:
     3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
     4         vector<int> res;
     5         if(matrix.size()==0) return res;
     6         if(matrix[0].size()==0) return res;
     7         int m=matrix.size(),n=matrix[0].size(),i=0,j=0;
     8         while(n>0&&m>0){
     9             res.push_back(matrix[i][j]);
    10             n--;
    11             m--;
    12             int step=n;
    13             while(step>0){
    14                 res.push_back(matrix[i][++j]);
    15                 step--;
    16             }
    17             step=m;
    18             while(step>0){
    19                 res.push_back(matrix[++i][j]);
    20                 step--;
    21             }
    22             if(m>0&&n>0){//判断有没有剩余的半圈
    23                 step=n--;//得到下一圈的n
    24                 while(step>0){
    25                     res.push_back(matrix[i][--j]);
    26                     step--;
    27                 }
    28                 step=--m;//得到下一圈的m
    29                 while(step>0){
    30                     res.push_back(matrix[--i][j]);
    31                     step--;
    32                 }
    33                 j++;
    34             }
    35         }
    36         return res;
    37     }
    38 };
  • 相关阅读:
    RAID技术
    敏捷开发
    如何写出高质量的代码?现在知道还不晚
    Java大型互联网架构技术经验
    Chrome精品插件
    2018 java BAT最新面试宝典
    Java成神之路(2018版)
    三分钟读懂摘要算法
    我的Mac应用清单
    事务隔离级别
  • 原文地址:https://www.cnblogs.com/Deribs4/p/5728429.html
Copyright © 2011-2022 走看看