풀이 방법
문제에 나온대로 구현을 통해 풀이했다.
board 판을 (N + 2) * (N + 2) 크기로 만들어서 벽을 생성해 주었고
way 배열에는 오른쪽, 아래, 왼쪽, 위 방향 순서대로 경로를 넣어주었고
map에 방향 전환 정보를 넣고 Queue로 뱀이 현재 위치한 정보를 담아주었다.
tail 함수는 뱀 머리가 뱀 몸통에 닿는지 확인하는 함수이다.
내 코드
package com.company;
import java.io.*;
import java.util.*;
public class Main {
static int N, K, L;
static int[][] board;
static int[][] way = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
static HashMap<Integer, String> map = new HashMap<>();
static Queue<int[]> q = new LinkedList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = null;
N = Integer.parseInt(br.readLine());
K = Integer.parseInt(br.readLine());
board = new int[N + 2][N + 2];
for (int i = 1; i <= N; i++) {
for (int j = 1; j <= N; j++) {
board[i][j] = 1;
}
}
for (int i = 0; i < K; i++) {
st = new StringTokenizer(br.readLine());
board[Integer.parseInt(st.nextToken())][Integer.parseInt(st.nextToken())] = 2;
}
L = Integer.parseInt(br.readLine());
for (int i = 0; i < L; i++) {
st = new StringTokenizer(br.readLine());
map.put(Integer.parseInt(st.nextToken()), st.nextToken());
}
int[] current = {1, 1};
int direction = 0;
int sec = 0;
q.add(current);
while (true) {
sec++;
String s = map.getOrDefault(sec, "not exist");
int[] next = {current[0] + way[direction][0], current[1] + way[direction][1]};
if (board[next[0]][next[1]] == 0 || tail(next)) {
break;
} else if (board[next[0]][next[1]] == 1) {
q.poll();
} else if (board[next[0]][next[1]] == 2) {
board[next[0]][next[1]] = 1;
}
q.add(next);
current[0] = next[0];
current[1] = next[1];
if (s.equals("D")) {
direction = (direction + 1) % 4;
} else if (s.equals("L")) {
direction = (direction + 3) % 4;
}
}
System.out.println(sec);
}
static boolean tail(int[] next) {
for (int[] array : q) {
if (array[0] == next[0] && array[1] == next[1])
return true;
}
return false;
}
}
'코딩테스트 > [백준] 코딩테스트 연습' 카테고리의 다른 글
십자가 2개 놓기 - 17085번 (0) | 2021.11.05 |
---|---|
Coins - 3067번 (0) | 2021.11.04 |
A -> B - 16953번 (0) | 2021.11.02 |
특정한 최단 경로 - 1504번 (0) | 2021.11.01 |
독서실 거리두기 - 20665번 (0) | 2021.10.27 |