Leetcode 059

来源:互联网 发布:围棋棋力测试软件 编辑:程序博客网 时间:2024/06/17 12:26

59. Spiral Matrix II

My Submissions
Total Accepted: 48287 Total Submissions: 141170 Difficulty: Medium

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));         if (n == 0 )           return res ;        int x = 0 , y = 0 ;        int cur = 1 ;              // memset(res , 0 ,sizeof(res) ) ;       res[0][0] = 1 ;       while ( cur < n*n ) {           while (y+1 < n && !res[x][y+1]) res[x][++y] = ++cur ;           while (x+1 < n && !res[x+1][y]) res[++x][y] = ++cur ;           while (y-1 >=0 && !res[x][y-1]) res[x][--y] = ++cur ;           while (x-1 >=0 && !res[x-1][y]) res[--x][y] = ++cur ;                  }          return res ;        }    };


0 0
原创粉丝点击