1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
| import java.util.*;
class Solution {
static int min;
static int[] dr = {0,-1,0,1};
static int[] dc = {-1,0,1,0};
static int[][] map;
static boolean[][] visited;
public static int solution(int[][] rectangle, int characterX, int characterY, int itemX, int itemY) {
int answer = 0;
min = Integer.MAX_VALUE;
map = new int[102][102];
visited = new boolean[102][102];
buildMap(rectangle);
map[itemY*2][itemX*2] = -1;
bfs(characterX*2,characterY*2,itemX*2,itemY*2);
answer = min/2;
return answer;
}
static void bfs(int cX, int cY, int iX, int iY){
Queue<int[]> q = new LinkedList<>();
q.add(new int[] {cY,cX,0});
visited[cY][cX] = true;
while(!q.isEmpty()){
int[] temp = q.poll();
int r = temp[0];
int c = temp[1];
int count = temp[2];
if(map[r][c] == -1){
min = Math.min(min,count);
}
for(int i = 0; i<4; i++){
int nr = r+dr[i];
int nc = c+dc[i];
if(nr < 0 || nr >= 102 || nc < 0 || nc >= 102) continue; // 범위 밖이면 제
if(visited[nr][nc] || map[nr][nc] == 0) continue; // 방문했거나 길이 아니면 제외
q.add(new int[] {nr,nc,count+1});
visited[nr][nc] = true;
}
}
}
static void buildMap(int[][] rectangle) {
for(int t = 0; t< rectangle.length; t++){ // 직사각형 채우기
int c1 = rectangle[t][0] *2;
int r1 = rectangle[t][1] *2;
int c2 = rectangle[t][2] *2;
int r2 = rectangle[t][3] *2;
for(int i = r1; i<=r2; i++){
for(int j = c1; j<=c2; j++){
map[i][j] = 1;
}
}
}
for (int t = 0; t < rectangle.length; t++) {
int c1 = rectangle[t][0] *2+1;
int r1 = rectangle[t][1] *2+1;
int c2 = rectangle[t][2] *2-1;
int r2 = rectangle[t][3] *2-1;
for(int i = r1; i<=r2; i++){
for(int j = c1; j<=c2; j++){
map[i][j] = 0;
}
}
}
}
}
|