2016年12月13日 星期二

[LeetCode] 59. Spiral Matrix II

轉自LeetCode

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

Spiral Matrix 的衍生題

這次是倒過來,將 1 到 n^2 的數,用螺旋的順序填到 n x n 的二維矩陣

既然題目是倒過來要求,其時解法也只有一行需要倒過來思考就好

之前是把二維陣列的值拿出來,現在就是把值塞回去二維陣列

其餘都是一樣

code 如下

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
if(n <= 0) {
return vector<vector<int>>();
}
vector<vector<int>> ans(n, vector<int>(n, -1));
const int total = n * n;
int cnt = 1, moveD = 0;
int r = 0, c = 0;
int rowUp = 0, rowDown = n;
int colLeft = -1, colRight = n;
while(cnt <= total) {
ans[r][c] = cnt++; //> put back to n x n array
switch(moveD) {
case 0: //> go right
if(++c == colRight) {
++r;
--colRight;
c = colRight;
moveD = 1;
}
break;
case 1: //> go down
if(++r == rowDown) {
--c;
--rowDown;
r = rowDown;
moveD = 2;
}
break;
case 2: //> go left
if(--c == colLeft) {
--r;
++colLeft;
c = colLeft;
moveD = 3;
}
break;
case 3: //> go up
if(--r == rowUp) {
++c;
++rowUp;
r = rowUp;
moveD = 0;
}
break;
}
}
return ans;
}
};

沒有留言:

張貼留言