您的位置:首页 > 其它

Leetcode Spiral Matrix II

2015-10-20 00:06 453 查看
Leetcode Spiral Matrix II 相关代码,本代码重用了Spiral Matrix 的相关代码。以下给出可运行代码,以及测试:

#include<iostream>
#include<vector>

using namespace std;

class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
// Record the four sides offset, 0: right, 1: down, 2: left, 3: up
vector<int> direction(4, 0);
vector<vector<int> > re(n, vector<int>(n, 0));
// foo control the four conditions of moving
int foo = 0;
// x, y record the current positon in matrix
int x = 0;
int y = -1;
int x_len = n;
int y_len = n;
int cur = 1;
while (direction[1] + direction[3] != n) {
switch(foo) {
// left-->right
case 0:
y ++;
for (; y < y_len - direction[foo]; y ++) {
re[x][y] = cur ++;
}
y --;
direction[3] ++;
break;
// up-->down
case 1:
x ++;
for (; x < x_len - direction[foo]; x ++) {
re[x][y] = cur ++;
}
x --;
direction[0] ++;
break;
// right-->left
case 2:
y --;
for (; y >= direction[foo]; y --) {
re[x][y] = cur ++;
}
y ++;
direction[1] ++;
break;
// down-->up
case 3:
x --;
for (; x >= direction[foo]; x --) {
re[x][y] = cur ++;
}
x ++;
direction[2] ++;
break;
}
foo = (++foo) % 4;
}
return re;
}
};

int main(int argc, char* argv[]) {
Solution so;
vector<vector<int> > re = so.generateMatrix(atoi(argv[1]));
for (int i = 0; i < re.size(); i ++) {
for (int j = 0; j < re[0].size(); j ++) {
cout<<re[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode