슈콩

[BOJ] 백준 3190 뱀 본문

Algorithms/Baekjoon

[BOJ] 백준 3190 뱀

shukong 2025. 10. 2. 14:45

[문제]

https://www.acmicpc.net/problem/3190

 

 

[소스 코드]

import java.io.*;
import java.util.*;

public class Main {
	static int[] dr = {0,1,0,-1};
	static int[] dc = {1,0,-1,0};
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		int n = Integer.parseInt(br.readLine());
		int[][] map = new int[n+1][n+1];
		int k = Integer.parseInt(br.readLine());
		for(int i=0;i<k;i++) {
			st = new StringTokenizer(br.readLine());
			int r = Integer.parseInt(st.nextToken());
			int c = Integer.parseInt(st.nextToken());
			map[r][c] = 1;
		}
		int l = Integer.parseInt(br.readLine());
		HashMap<Integer,String> hm = new HashMap<>();
		for(int i=0;i<l;i++) {
			st = new StringTokenizer(br.readLine());
			int x = Integer.parseInt(st.nextToken());
			String c = st.nextToken();
			hm.put(x, c);
		}
		boolean[][] visit = new boolean[n+1][n+1];
		Deque<int[]> q = new LinkedList<>();
		visit[1][1] = true;
		q.offer(new int[] {1,1});
		int time = 1;
		int d = 0;
		while(!q.isEmpty()) {
			int[] head = q.peekLast();
			int nr = head[0] + dr[d];
			int nc = head[1] + dc[d];
			if(nr<1 || nr>n || nc<1 || nc>n || visit[nr][nc]) break;
			if(map[nr][nc]==1) {
				map[nr][nc] = 0;
			}
			else {
				int[] tail = q.poll();
				visit[tail[0]][tail[1]] = false;
			}
			visit[nr][nc] = true;
			q.offer(new int[] {nr,nc});
			
			if(hm.containsKey(time)) {
				String c = hm.get(time);
				if(c.equals("L")) d = (d+3) % 4;
				else d = (d+1) % 4;
			}
			time++;
		}
		System.out.println(time);
	}
}

'Algorithms > Baekjoon' 카테고리의 다른 글

[BOJ] 백준 28215 대피소  (0) 2025.10.04
[BOJ] 백준 13458 시험 감독  (0) 2025.10.02
[BOJ] 백준 9205 맥주 마시면서 걸어가기  (0) 2025.09.30
[BOJ] 백준 2573 빙산  (0) 2025.09.30
[BOJ] 백준 2468 안전 영역  (0) 2025.09.30