leetcode59. 螺旋矩阵 II
生活随笔
收集整理的這篇文章主要介紹了
leetcode59. 螺旋矩阵 II
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
一:題目
二:上碼
class Solution { public:/**思路:1.這個就是模擬螺旋的過程2.我們要注意的是邊界條件 我們采用的左閉右開3.我們在模擬的過程中 進(jìn)行填數(shù)。*/vector<vector<int>> generateMatrix(int n) {vector<vector<int> >ans(n,vector<int>(n,0));int loop = n/2;//邊數(shù)int startx = 0;int starty = 0;int border = 1;//邊界值int count = 0;int i,j;//全局變量 就是一直在變化模擬螺旋的過程while (loop--) {i = startx;j = starty;//最上面的一行 行不動 列在動for (j = starty; j < n - border; j++){count++;ans[i][j] = count;} //最右面的一行 行不動for (i = startx; i < n - border; i++) {count++;ans[i][j] = count;}//最下面的一行for (; j >= border; j--) {//大于等于border 因為我們是作閉右開 所以的話 //我們是取不到右邊的count++;ans[i][j] = count;}//最左面的一行for (; i >= border; i--) {count++;ans[i][j] = count;} startx++;starty++;border++;}//當(dāng)n為奇數(shù)的時候 我們需要將中間的數(shù)計算進(jìn)去if(n%2 != 0) {int mid = n/2;count++;ans[mid][mid] = count;}return ans;} };
做過就是不一樣啊 思路和速度就快了
總結(jié)
以上是生活随笔為你收集整理的leetcode59. 螺旋矩阵 II的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是骨裂
- 下一篇: leetcode剑指 Offer 29.