이번에는 재귀호출을 쓰지 않고 Loop로 풀어봤다..
메모리를 좀 많이 쓰는 코드인데, 자료형을 조금 손 보거나 map을 만들지 않는 방법도 개선점으로 둘 수 있을 것 같다.
class Solution {
int map[20][20];
int direction[4][2] = {
{0, 1}, {1, 0}, {0, -1}, {-1, 0}
};
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> r;
int cur_x = -1;
int cur_y = 0;
int marker = 1;
int last_marker = n * n;
while( marker <= last_marker )
{
for ( int i = 0; i < 4; i++ )
{
while(1)
{
cur_y = cur_y + direction[i][0];
cur_x = cur_x + direction[i][1];
if ( cur_y < 0 || cur_y >= n || cur_x < 0 || cur_x >= n || map[cur_y][cur_x] != 0)
{
cur_y = cur_y - direction[i][0];
cur_x = cur_x - direction[i][1];
break;
}
map[ cur_y ][ cur_x ] = marker++;
}
}
}
for ( int i = 0; i < n; i++)
{
vector<int> row;
for( int j = 0; j < n; j++)
row.push_back ( map[i][j] );
r.push_back(row);
}
return r;
}
};
'Algorithm things' 카테고리의 다른 글
[Leetcode] 696. Count Binary Substrings (0) | 2021.04.27 |
---|---|
[Algorithm] Karatsuba algorithm (0) | 2021.03.31 |
[LeetCode] 54. Spiral Matrix (0) | 2021.03.30 |
[LeetCode] LeetCode 풀이를 할때 IDE를 써야할까 (6) | 2021.03.27 |
[LeetCode] Weekly Contest 234 (0) | 2021.03.27 |