- 배열 / LinkedList / Matrix 문제
https://leetcode.com/problems/spiral-matrix-iv/description/?envType=daily-question&envId=2024-09-09
- 문제분석
1. ListNode head 의 원소값과 m (row) x n (col) 로 되어있는 행렬이 있다.
2. 해당 행렬을 시계방향으로 head 의 원소값을 채워나간다.
3. 빈 값에는 -1을 입력한다.
4. 2차원 배열로 출력하시오.
- 문제풀이
1. ListNode head 값을 Queue 에 담아 2차원배열에 입력할 수 있도록 한다.
2. 시계방향으로 입력하기 위해서는 left -> down -> right -> up 의 순서대로 2차원 배열을 순회할 수 있어야한다.
3. 이때, 방향을 입력할 수 있도록 int[][] directions = { left, down, right, up } 을 초기화한다.
3-1. left = {0,1}, down = {1,0} , right = {0,-1}, up = {-1,0} 로 초기화하여 순회할 수 있도록한다.
3-2. 또한 m = 3, n =5 일때, 3x5 를 순회하기 위한 규칙을 이해한다.
3-3. left (5) -> down(3-1) -> right(5-1) -> up (3-2) -> left ( 5-2 ) -> down (3-3)...
3-4. down 과 up 을 거칠때마다 m-i, n-i 의 i 값이 증가함으로 해당 증가식을 더한다.
4. totalSize = mxn 으로 초기화하여 증감하여 전부 순회하였는지 확인한다.
5. now 값을 = { 0, -1 } 로 초기화하여 left 부터 순서대로 회전할 수 있도록 한다.
6. now[0] += directions[i][0] , now[1] += directions[i][0] 값으로 순회한다.
class Solution {
/**
*/
public int[][] spiralMatrix(int m, int n, ListNode head) {
//head 값을 순회하여 queue 에 담는다.
Queue<Integer> queue = new LinkedList<>();
find(head, queue);
int[][] answer = new int[m][n];
int[] now = {0,-1}; // left 로 출발하기 위해 {0,-1} 로 초기화
int[][] directions = {{0,1},{1,0},{0,-1},{-1,0}}; // left, down, right, up
int totalSize = m*n; // Matrix 총사이즈
int nextIdx = 0; // down, up 일때 증가시켜 시계방향으로 회전시킨다.
int size = 0; // left, right 일때 n 값을, down, up 일때 m 값으로 초기화하는 변수
while(totalSize > 0) {
for (int i = 0; i < 4; i++) {
if (i == 1 || i == 3) {
nextIdx++;
}
if (i%2 == 0) {
size = n;
} else {
size = m;
}
int length = size-nextIdx; // 반복할 값 ( ex) 5-1 )
for(int j = 0; j < length; j++) {
now[0]+=directions[i][0];
now[1]+=directions[i][1];
answer[now[0]][now[1]] = queue.isEmpty() ? -1 : queue.poll();
}
totalSize-=length;
if (totalSize == 0) break;
}
}
return answer;
}
void find(ListNode head, Queue<Integer> queue) {
if (head == null) {
return;
}
queue.offer(head.val);
find(head.next, queue);
}
}
'TIL' 카테고리의 다른 글
[FrontEnd] WebPack (1) | 2024.09.12 |
---|---|
[코테연습] 2220. Minimum Bit Flips to Convert Number (1) | 2024.09.11 |
[코테연습] 874. Walking Robot Simulation (0) | 2024.09.05 |
[코테연습] 1894. Find the Student that Will Replace the Chalk (0) | 2024.09.02 |
[코테연습] 야근 지수 (0) | 2024.08.30 |