zoukankan      html  css  js  c++  java
  • 59. Spiral Matrix && Spiral Matrix II

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

    思路: 可参考剑指offer:题20

    class Solution {
    public:
        vector<int> spiralOrder(vector<vector<int> > &matrix) {
            vector<int> vec;
            if(!matrix.size() || !matrix[0].size()) return vec;
            int row = matrix.size(), col = matrix[0].size();
            int rl = 0, rh = row-1, cl = 0, ch = col-1;
            while(rh >= rl && ch >= cl) {
                for(int c = cl; c <= ch; ++c) vec.push_back(matrix[rl][c]);
                if(++rl > rh) break;
                for(int r = rl; r <= rh; ++r) vec.push_back(matrix[r][ch]);
                if(--ch < cl) break;
                for(int c = ch; c >= cl; --c) vec.push_back(matrix[rh][c]);
                --rh;
                for(int r = rh; r >= rl; --r) vec.push_back(matrix[r][cl]);
                ++cl;
            }
            return vec;
        }
    };
    

    Spiral Matrix II

    Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

    For example, Given n = 3,

    You should return the following matrix:

    [
     [ 1, 2, 3 ],
     [ 8, 9, 4 ],
     [ 7, 6, 5 ]
    ]
    
    class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int> > vec(n, vector<int>(n));
            int rl = 0, rh = n-1, cl = 0, ch = n-1, v = 1;
            while(rh >= rl && ch >= cl) {
                for(int c = cl; c <= ch; ++c) vec[rl][c] = v++;
                if(++rl > rh) break;
                for(int r = rl; r <= rh; ++r) vec[r][ch] = v++;
                if(--ch < cl) break;
                for(int c = ch; c >= cl; --c) vec[rh][c] = v++;
                --rh;
                for(int r = rh; r >= rl; --r) vec[r][cl] = v++;
                ++cl;
            }
            return vec;
        }
    };
    
  • 相关阅读:
    错题本
    前端常用的代码片段
    前端生成二维码 jquery.qrcode.js
    jquery获取第几个元素的方法总结
    Jquery 获取第一个子元素
    个人作品(2016.3.17更新)
    360度全景制作
    期末项目_通用教学管理系统(季远琦&庞思瑶)
    java ee 第四周作业
    Web Service和EJB的区别
  • 原文地址:https://www.cnblogs.com/liyangguang1988/p/3961165.html
Copyright © 2011-2022 走看看