슈콩

[BOJ] 백준 3190 뱀 본문

Algorithms/Baekjoon

[BOJ] 백준 3190 뱀

shukong 2025. 8. 17. 17:47

[문제]

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

 

 

[소스 코드]

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

public class Main {
	static int n,dir=0;
	static int[][] board;
	static Map<Integer,String> moveInfo;
	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 = new StringTokenizer(br.readLine());
    	n = Integer.parseInt(st.nextToken());
    	board = new int[n][n];
    	st = new StringTokenizer(br.readLine());
    	int k = Integer.parseInt(st.nextToken());
    	for(int i=0;i<k;i++) {
    		st = new StringTokenizer(br.readLine());
    		int a = Integer.parseInt(st.nextToken()) - 1;
    		int b = Integer.parseInt(st.nextToken()) - 1;
    		board[a][b] = 1;
    	}
    	st = new StringTokenizer(br.readLine());
    	int l = Integer.parseInt(st.nextToken());
    	moveInfo = new HashMap<>();
    	for(int i=0;i<l;i++) {
    		st = new StringTokenizer(br.readLine());
    		int time = Integer.parseInt(st.nextToken());
    		String direction = st.nextToken();
    		moveInfo.put(time, direction);
    	}
    	bfs();
    }
    private static void bfs() {
    	Queue<Integer> q = new LinkedList<>();
    	q.offer(0);
    	int r = 0;
    	int c = 0;
    	int time = 0;
    	while(true) {
    		time++;
    		int nr = r + dr[dir];
    		int nc = c + dc[dir];
    		if(nr<0 || nc<0 || nr>=n || nc>=n) break;
    		if(q.contains(nr*n+nc)) break;
    		if(board[nr][nc]==1) {
    			q.offer(nr*n+nc);
    			board[nr][nc] = 0;
    		}
    		else {
    			q.offer(nr*n+nc);
    			q.poll();
    		}
    		if(moveInfo.containsKey(time)) {
    			if(moveInfo.get(time).equals("D"))
    				dir = (dir+1) % 4;
    			else
    				dir = (dir+3) % 4;
    		}
    		r = nr;
    		c = nc;
    	}
    	System.out.println(time);
    }
}

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

[BOJ] 백준 5373 큐빙  (0) 2025.08.18
[BOJ] 백준 4991 로봇청소기  (2) 2025.08.17
[BOJ] 백준 2478 자물쇠  (2) 2025.08.17
[BOJ] 백준 23291 어항 정리  (2) 2025.08.13
[BOJ] 백준 23290 마법사 상어와 복제  (2) 2025.08.12