코드와이
[BAEKJOON] 1600. 말이 되고픈 원숭이 본문
그래프 이론
그래프 탐색
BFS
문제링크
1600번: 말이 되고픈 원숭이
첫째 줄에 정수 K가 주어진다. 둘째 줄에 격자판의 가로길이 W, 세로길이 H가 주어진다. 그 다음 H줄에 걸쳐 W개의 숫자가 주어지는데, 0은 아무것도 없는 평지, 1은 장애물을 뜻한다. 장애물이 있
www.acmicpc.net
package acmicpc.Gold5;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class 말이_되고픈_원숭이 {
static class Monkey{
int r;
int c;
int jump;
int sum;
public Monkey(int r, int c, int jump, int sum) {
super();
this.r = r;
this.c = c;
this.jump = jump;
this.sum = sum;
}
}
static int[] dr = {-1,1,0,0};
static int[] dc = {0,0,-1,1};
static int[] dr2 = {-2,-1,1,2,2,1,-1,-2};
static int[] dc2 = {1,2,2,1,-1,-2,-2,-1};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int k = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
int m = Integer.parseInt(st.nextToken());
int n = Integer.parseInt(st.nextToken());
int[][] arr = new int[n][m];
boolean[][][] visited = new boolean[n][m][k+1];
for(int i = 0 ; i < n ; i++) {
st = new StringTokenizer(br.readLine());
for(int j = 0 ; j < m ; j++) {
arr[i][j] = Integer.parseInt(st.nextToken());
}
}
int ans = -1;
Queue<Monkey> queue = new LinkedList<Monkey>();
queue.add(new Monkey(0,0,k,0));
while(!queue.isEmpty()) {
Monkey q = queue.poll();
if(q.r == n-1 && q.c == m-1) {
ans = q.sum;
break;
}
if(visited[q.r][q.c][q.jump]) continue;
visited[q.r][q.c][q.jump] = true;
for(int d = 0 ; d < 4 ; d++) {
int nr = q.r + dr[d];
int nc = q.c + dc[d];
if(nr < 0 || nc < 0 || nr >= n || nc >= m || arr[nr][nc] == 1) continue;
queue.add(new Monkey(nr, nc, q.jump, q.sum + 1));
}
if(q.jump == 0) continue;
for(int d = 0 ; d < 8 ; d++) {
int nr = q.r + dr2[d];
int nc = q.c + dc2[d];
if(nr < 0 || nc < 0 || nr >= n || nc >= m || arr[nr][nc] == 1) continue;
queue.add(new Monkey(nr,nc,q.jump-1,q.sum+1));
}
}
System.out.println(ans == -1 ? -1 : ans);
}
}
'acmicpc' 카테고리의 다른 글
[BAEKJOON] 11055. 가장 큰 증가 부분 수열 (0) | 2021.03.25 |
---|---|
[SW Expert Academy] 3308. 최장 증가 부분 수열 (Hard) (0) | 2021.03.25 |
[BAEKJOON] 2096. 내려가기 (0) | 2021.03.24 |
[BAEKJOON] 11048. 이동하기 (0) | 2021.03.24 |
[BAEKJOON] 2839. 설탕 배달(DP) (0) | 2021.03.23 |