leetcode-59 Spiral Matrix

来源:互联网 发布:如何申请开淘宝网店 编辑:程序博客网 时间:2024/04/29 14:47

这是一道旋转矩阵的题,题目如下:

Given an integer n, generate a square matrix filled with elements from 1 ton2 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;//row,col控制每一圈需要打印的行数和列数,随着循环圈数递减int row = n-1;int col = n-1;//x,y每一圈的起始位置,i,j动态控制位置int x, y, i, j;int tempn = 1;for (x = 0, y = 0; x <= row&&y <= col; x++, y++){//存储最上面一行,需要改变列号,列起始位置j随着y在变换for (j = y; j <= col; j++){res[x][j] = tempn;tempn++;}//存储最右边一列,行起始位置随着x在变换for (i = x+1; i <= row; i++){res[i][col] = tempn;tempn++;}//存储最下面一列,列末起始位置随着col在变换for (j = col - 1; j >= y; j--){res[row][j] = tempn;tempn++;}//存储最右边for (i = row - 1; i > x; i--){res[i][y] = tempn;tempn++;}row--;col--;}return res;}};


0 0
原创粉丝点击