Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions lkhyun/202508/25 BOJ G3 보물 찾기 2.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
```java
import java.util.*;
import java.io.*;

public class Main{
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
static StringTokenizer st;
static StringBuilder sb = new StringBuilder();
static int H,W;
static char[][] map;
static int starti,startj;
static int[] di = {-1,0,1,1,1,0,-1,-1};
static int[] dj = {1,1,1,0,-1,-1,-1,0};

public static void main(String[] args) throws Exception {
st = new StringTokenizer(br.readLine());
H = Integer.parseInt(st.nextToken());
W = Integer.parseInt(st.nextToken());

map = new char[H][W];

for (int i = 0; i < H; i++) {
char[] line = br.readLine().toCharArray();
for (int j = 0; j < W; j++) {
map[i][j] = line[j];
if(line[j] == 'K'){
starti = i;
startj = j;
}
}
}

bw.write(BFS()+"");
bw.close();
}
public static int BFS(){
ArrayDeque<int[]> q = new ArrayDeque<>();
int[][] dist = new int[H][W];
for (int i = 0; i < H; i++) {
Arrays.fill(dist[i], Integer.MAX_VALUE);
}
q.offer(new int[]{starti,startj,0});
dist[starti][startj] = 0;

while(!q.isEmpty()){
int[] cur = q.poll();
if(map[cur[0]][cur[1]] == '*') return dist[cur[0]][cur[1]];
if(dist[cur[0]][cur[1]] < cur[2]) continue;

for (int k = 0; k < 3; k++) {
int ni = cur[0] + di[k];
int nj = cur[1] + dj[k];
if(check(ni,nj)){
if(dist[ni][nj] > cur[2]){
q.addFirst(new int[]{ni,nj,cur[2]});
dist[ni][nj] = cur[2];
}
}
}
for (int k = 3; k < 8; k++) {
int ni = cur[0] + di[k];
int nj = cur[1] + dj[k];
if(check(ni,nj)){
if(dist[ni][nj] > cur[2]+1){
q.addLast(new int[]{ni,nj,cur[2]+1});
dist[ni][nj] = cur[2]+1;
}
}
}
}
return -1;
}
public static boolean check(int i, int j){
if(i < 0 || i >= H || j < 0 || j >= W || map[i][j] == '#') return false;
return true;
}
}
```