반응형
풀이
문제 대로 구현하면 되는 문제지만,
푸는데 꽤 오래 걸렸습니다.
원인은 방향 인덱스
bfs로 풀고, 방향 인덱스를 잘 못 갱신해줬었습니다 !
풀이는 로봇 위치와 장애물 위치, 방향을 입력 받고,
맵 밖에 나가거나, 방문한 위치를 방문하거나, 장애물을 만나면 방향을 바꾸면 바꿔
다른 방향으로 탐색하는 식으로 풀었습니다.
import java.io.*;
import java.util.*;
public class Main{
static int K, R, C, curX, curY, dirIdx;
static int[][] map;
static boolean[][] visited;
static int[] dir = new int[4];
//상 하 좌 우
static int[] dx = {-1,1,0,0};
static int[] dy = {0,0,-1,1};
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
map = new int[R][C];
visited = new boolean[R][C];
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] = 2;
}
st = new StringTokenizer(br.readLine());
curX = Integer.parseInt(st.nextToken());
curY = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
for(int i = 0 ; i < 4; i++) {
dir[i] = Integer.parseInt(st.nextToken()) - 1;
}
bfs();
System.out.println(curX+" "+curY);
}
private static void bfs() {
Queue<int []> queue = new LinkedList<int[]>();
visited[curX][curY] = true;
queue.offer(new int[] {curX, curY});
while(! queue.isEmpty()) {
int[] cur = queue.poll();
for(int i = 0 ; i < 4; i++) {
int d = dir[(dirIdx + i) % 4];
int nx = cur[0] + dx[d];
int ny = cur[1] + dy[d];
if(0 > nx || nx >= R || 0 > ny || ny >= C || visited[nx][ny] == true || map[nx][ny] == 2) continue;
visited[nx][ny] = true;
queue.offer(new int[] {nx, ny});
dirIdx = (dirIdx + i) % 4;
curX = nx;
curY = ny;
break;
}
}
}
}
반응형
'알고리즘 > 문제 풀이' 카테고리의 다른 글
[Java/자바 백준 2234] 성곽 (0) | 2022.02.03 |
---|---|
[Java/자바 백준 2174] 로봇 시물레이션 (0) | 2022.02.03 |
[Java/자바 백준 11559] PuyoPuyo (0) | 2022.01.18 |
[Java/자바 백준 1062] 가르침 (0) | 2022.01.18 |
[Java/자바 백준 21609] 상어 중학교 (0) | 2022.01.15 |