標籤:style blog http io color ar 使用 for sp
題目:是Spiral Matrix相關的的。這題的意思是給定一個n,那麼在n*n的矩陣裡按照迴圈記錄將1,2,3,..., n*n。如下如果給定3,那麼:
[ [ 1, 2, 3 ], [ 8, 9, 4 ], [ 7, 6, 5 ]]
一開始我想是不是有數學公式直接下標對應的,那直接遍曆輸出就可以了。但是推了一會,沒有什麼好的頭緒。於是就分情況討論了,和Spiral Matrix一樣的分情況,只是這裡的分情況是記錄在數組裡面。
利用上,下,左,右,分別記錄每次迴圈可以到達的四個邊界,我們每次就輸出一環,走完一環往內走。
需要注意的:
1.要用下標訪問vector<vector> >需要先聲明大小才可以使用下標訪問。
2.每走完一環,相應更新四個方向。
3.如果是奇數,那麼n*n這個數需要另外存。也就是存在[n/2][n/2]的位置。
class Solution {public:vector<vector<int> > generateMatrix(int n){ vector<int> sub(n); vector<vector<int> > ans(n, sub); // 也可以用vector<vector<int> > ans(n, vector<int>(n)); if (n < 1) return ans; int val = 1, left = 0, right = n-1, up = 1, down = n-1; for (int i = 0; i < n/2; i++) { for (int j = left; j <= right; j++) { ans[i][j] = val++; } for (int j = up; j <= down; j++) { ans[j][right] = val++; } for (int j = right - 1; j>=left; j--) { ans[down][j] = val++; } for (int j = down - 1; j >= up; j--) { ans[j][left] = val++; } left++; right--; up++; down--; } if (n%2) ans[n/2][n/2] = n*n; return ans;}};
leetcode Spiral Matrix II