개발 일지
59. Spiral Matrix II (나선형 매트릭스 II) 본문
양의 정수 n이 주어졌을 때, 1부터 n^2까지의 원소를 나선형으로 채운 n*n 행렬을 생성합니다.
예시 1:
입력: n = 3
출력: [[1,2,3],[8,9,4],[7,6,5]]
예시 2:
입력: n = 1
출력: [[1]]
조건:
- 1 <= n <= 2
정답:
public class Solution
{
public int[][] GenerateMatrix(int n)
{
int[][] result = new int[n][];
for (int i = 0; i < n; i++)
{
result[i] = new int[n];
}
int value = 1;
string mod = "yplus";
bool once = false;
int x = 0;
int y = -1;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
switch (mod)
{
case "xplus":
x += 1;
if (x == n || result[x][y] != 0)
{
x -= 1;
mod = "yminus";
once = true;
}
break;
case "xminus":
x -= 1;
if (x < 0 || result[x][y] != 0)
{
x += 1;
mod = "yplus";
once = true;
}
break;
case "yplus":
y += 1;
if (y == n || result[x][y] != 0)
{
y -= 1;
mod = "xplus";
once = true;
}
break;
case "yminus":
y -= 1;
if (y < 0 || result[x][y] != 0)
{
y += 1;
mod = "xminus";
once = true;
}
break;
}
if (once)
{
switch (mod)
{
case "xplus":
x += 1;
break;
case "xminus":
x -= 1;
break;
case "yplus":
y += 1;
break;
case "yminus":
y -= 1;
break;
}
once = false;
}
result[x][y] = value;
value += 1;
}
}
return result;
}
}
해설: siwtch case로 일관적으로 값을 처리할 수 있도록 mod를 지정하고 값이 이미 들어간 매트릭스이거나 매트릭스의 값을 크기를 넘어갈 때 관련해서 값이 처리될 수 있도록 mod를 변경하여 해결하였습니다.
'코딩 테스트 > LeetCode' 카테고리의 다른 글
46. Permutations (순열) (0) | 2024.04.08 |
---|---|
28. Find the Index of the First Occurrence in a String (문자열에서 첫 번째 발생 인덱스 찾기) (0) | 2024.03.21 |
27. Remove Element (요소 제거) (0) | 2024.03.19 |
1337. The K Weakest Rows in a Matrix (행렬에서 가장 약한 K 행) (0) | 2023.11.03 |
565. Array Nesting (배열 중첩) (0) | 2023.11.01 |