Skip to content

Commit 9a85e3a

Browse files
authored
Merge pull request #738 from AlgorithmWithGod/lkhyun
[20250825] BOJ / G3 / 보물 찾기 2 / 이강현
2 parents 0e6ef7f + b0cb449 commit 9a85e3a

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
```java
2+
import java.util.*;
3+
import java.io.*;
4+
5+
public class Main{
6+
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
7+
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
8+
static StringTokenizer st;
9+
static StringBuilder sb = new StringBuilder();
10+
static int H,W;
11+
static char[][] map;
12+
static int starti,startj;
13+
static int[] di = {-1,0,1,1,1,0,-1,-1};
14+
static int[] dj = {1,1,1,0,-1,-1,-1,0};
15+
16+
public static void main(String[] args) throws Exception {
17+
st = new StringTokenizer(br.readLine());
18+
H = Integer.parseInt(st.nextToken());
19+
W = Integer.parseInt(st.nextToken());
20+
21+
map = new char[H][W];
22+
23+
for (int i = 0; i < H; i++) {
24+
char[] line = br.readLine().toCharArray();
25+
for (int j = 0; j < W; j++) {
26+
map[i][j] = line[j];
27+
if(line[j] == 'K'){
28+
starti = i;
29+
startj = j;
30+
}
31+
}
32+
}
33+
34+
bw.write(BFS()+"");
35+
bw.close();
36+
}
37+
public static int BFS(){
38+
ArrayDeque<int[]> q = new ArrayDeque<>();
39+
int[][] dist = new int[H][W];
40+
for (int i = 0; i < H; i++) {
41+
Arrays.fill(dist[i], Integer.MAX_VALUE);
42+
}
43+
q.offer(new int[]{starti,startj,0});
44+
dist[starti][startj] = 0;
45+
46+
while(!q.isEmpty()){
47+
int[] cur = q.poll();
48+
if(map[cur[0]][cur[1]] == '*') return dist[cur[0]][cur[1]];
49+
if(dist[cur[0]][cur[1]] < cur[2]) continue;
50+
51+
for (int k = 0; k < 3; k++) {
52+
int ni = cur[0] + di[k];
53+
int nj = cur[1] + dj[k];
54+
if(check(ni,nj)){
55+
if(dist[ni][nj] > cur[2]){
56+
q.addFirst(new int[]{ni,nj,cur[2]});
57+
dist[ni][nj] = cur[2];
58+
}
59+
}
60+
}
61+
for (int k = 3; k < 8; k++) {
62+
int ni = cur[0] + di[k];
63+
int nj = cur[1] + dj[k];
64+
if(check(ni,nj)){
65+
if(dist[ni][nj] > cur[2]+1){
66+
q.addLast(new int[]{ni,nj,cur[2]+1});
67+
dist[ni][nj] = cur[2]+1;
68+
}
69+
}
70+
}
71+
}
72+
return -1;
73+
}
74+
public static boolean check(int i, int j){
75+
if(i < 0 || i >= H || j < 0 || j >= W || map[i][j] == '#') return false;
76+
return true;
77+
}
78+
}
79+
```

0 commit comments

Comments
 (0)