Skip to content

Commit 6c9e2db

Browse files
authored
BOJ #17836: 공주님을 구해라!
1 parent 465c1b0 commit 6c9e2db

File tree

1 file changed

+77
-0
lines changed

1 file changed

+77
-0
lines changed

BOJ/17836/Main.java

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
* Author: Minho Kim (ISKU)
3+
* Date: December 6, 2019
4+
* E-mail: minho.kim093@gmail.com
5+
*
6+
* https://github.com/ISKU/Algorithm
7+
* https://www.acmicpc.net/problem/17836
8+
*/
9+
10+
import java.io.*;
11+
import java.util.*;
12+
13+
public class Main {
14+
15+
public static final int[] dy = { -1, 1, 0, 0 };
16+
public static final int[] dx = { 0, 0, -1, 1 };
17+
public static final int MAX = 500000;
18+
19+
private static int[][] map;
20+
private static int Y, X, T;
21+
22+
public static void main(String[] args) throws Exception {
23+
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
24+
StringTokenizer st = new StringTokenizer(br.readLine());
25+
Y = Integer.parseInt(st.nextToken());
26+
X = Integer.parseInt(st.nextToken());
27+
T = Integer.parseInt(st.nextToken());
28+
29+
int pcount = 0;
30+
map = new int[Y][X];
31+
for (int y = 0; y < Y; y++) {
32+
st = new StringTokenizer(br.readLine());
33+
for (int x = 0; x < X; x++) {
34+
map[y][x] = Integer.parseInt(st.nextToken());
35+
if (map[y][x] == 2)
36+
pcount = (Y - 1 - y) + (X - 1 - x);
37+
}
38+
}
39+
40+
int first = bfs(1);
41+
int second = bfs(2);
42+
if (first == MAX && second == MAX || (first > T && second + pcount > T)) {
43+
System.out.println("Fail");
44+
System.exit(0);
45+
}
46+
System.out.println((first < second + pcount) ? first : second + pcount);
47+
}
48+
49+
private static int bfs(int target) {
50+
Queue<int[]> q = new LinkedList<>();
51+
int[][] visited = new int[Y][X];
52+
53+
q.add(new int[] { 0, 0 });
54+
while (!q.isEmpty()) {
55+
int[] p = q.poll();
56+
int py = p[0];
57+
int px = p[1];
58+
int count = visited[py][px];
59+
if (target == 1 && py == Y - 1 && px == X - 1)
60+
return count;
61+
if (target == 2 && map[py][px] == 2)
62+
return count;
63+
64+
for (int i = 0; i < 4; i++) {
65+
int y = py + dy[i];
66+
int x = px + dx[i];
67+
if (y < 0 || y >= Y || x < 0 || x >= X || visited[y][x] > 0 || map[y][x] == 1)
68+
continue;
69+
70+
visited[y][x] = count + 1;
71+
q.add(new int[] { y, x });
72+
}
73+
}
74+
75+
return MAX;
76+
}
77+
}

0 commit comments

Comments
 (0)