zoukankan      html  css  js  c++  java
  • Leetcode 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> > res(n,vector<int>(n,0));
            int dx[] = {0,1,0,-1};
            int dy[] = {1,0,-1,0};
            int cnt = 1,step = 0,x = 0 , y = 0;
            while(cnt <= n*n){
                step%=4;
                res[x][y] = cnt++;
                if(x+dx[step] >=n || x+dx[step] < 0 || y+dy[step] >=n || y+dy[step] < 0 || res[x+dx[step]][y+dy[step]]) step++;
                x+=dx[step%4];y+=dy[step%4];
            }
            return res;
        }
    };
  • 相关阅读:
    Binary Tree Paths
    Implement Stack using Queues
    Path Sum II
    Path Sum
    Plus One
    Add Digits
    Missing Number
    H-Index II
    H-Index
    Ugly Number II
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/3809013.html
Copyright © 2011-2022 走看看