-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEx07_06.java
More file actions
83 lines (77 loc) ยท 3.18 KB
/
Copy pathEx07_06.java
File metadata and controls
83 lines (77 loc) ยท 3.18 KB
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
76
77
78
79
80
81
82
83
package study.inflearn.lecture02.section07;
import java.util.LinkedList;
import java.util.Queue;
/**
* ์ฒ์์ ๊ธฐ์ฌ - ๋์ด์ฐ์ ํ์ : BFS
* ๊ฐ์ฌ๋ ํด๋ฒ ๋ฃ๊ณ ์ฌ๋์
*/
public class Ex07_06 {
public int solution(int[][] board){
int answer = 0;
int xLen = board.length;
int yLen = board[0].length;
int[] dx = {-1, 0, 1, 0};
int[] dy = {0, 1, 0, -1};
Queue<int[]> Q = new LinkedList<>();
int[][] dist = new int[xLen][yLen]; // ๊ฑฐ๋ฆฌ
int[][] ch; // ๋ฐฉ๋ฌธ์ง์ ์ฒดํฌ
for (int i = 0; i < xLen; i++) {
for (int j = 0; j < yLen; j++) {
if (board[i][j] == 2 || board[i][j] == 3) { // ์ํฌ/๊ธฐ์ฌ => ์ํฌ๋ก ๋ณด๊ธฐ
ch = new int[xLen][yLen]; // ์ํฌ/๊ธฐ์ฌ ๊ฐ๊ฐ ๋ฐฉ๋ฌธ์ง์ ์ด๊ธฐํ
Q.offer(new int[]{i, j});
ch[i][j] = 1; // ๋ฐฉ๋ฌธ์ง์ ์ฒดํฌ ์ํ๋๋ฐ ์ ๋ต๋์ด.
int L = 0;
while(!Q.isEmpty()){
L++;
// ๋ ๋ฒจ ํ์
int len = Q.size();
for(int k = 0; k < len; k++){
int[] cur = Q.poll();
// ์์๋ ๋ฒจ ํ์
for(int z = 0; z < 4; z++){
int nx=cur[0]+dx[z];
int ny=cur[1]+dy[z];
if (nx < 0 || ny < 0 || nx >= xLen || ny >= yLen || board[nx][ny] == 1) continue;
if (nx >= 0 && ny >= 0 && nx < xLen && ny < yLen && ch[nx][ny] == 0){
dist[nx][ny] += L;
ch[nx][ny] = 1;
Q.offer(new int[]{nx, ny});
}
}
}
}
}
}
}
// ์ฐ๋ธ๊ธฐ ์ง์ ์ต๋จ๊ฑฐ๋ฆฌ ๊ตฌํ๊ธฐ
answer = Integer.MAX_VALUE;
for (int i = 0; i < xLen; i++) {
for (int j = 0; j < yLen; j++) {
if (board[i][j] == 4 && dist[i][j] > 0) { // dist[i][j] > 0 ๋์๋จ๋ถ ๋ค ๋งํ์ ๊ฒฝ์ฐ
answer = Math.min(answer,dist[i][j]);
}
}
}
return answer;
}
public static void main(String[] args){
Ex07_06 T = new Ex07_06();
System.out.println(T.solution(new int[][]{{4, 1, 0, 0, 0, 0, 1, 0},
{0, 0, 0, 1, 0, 1, 0, 0},
{0, 2, 1, 1, 3, 0, 4, 0},
{0, 0, 0, 4, 1, 1, 1, 0}}));
System.out.println(T.solution(new int[][]{{3, 0, 0, 0, 1, 4, 4, 4},
{0, 1, 1, 0, 0, 0, 1, 0},
{0, 1, 4, 0, 1, 0, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 0},
{1, 0, 1, 0, 0, 1, 1, 0},
{4, 0, 0, 0, 1, 0, 0, 0},
{4, 1, 0, 0, 1, 0, 0, 0},
{4, 0, 0, 0, 0, 0, 1, 2}}));
System.out.println(T.solution(new int[][]{{4, 1, 0, 1, 0},
{0, 1, 0, 1, 0},
{0, 0, 2, 3, 4},
{0, 1, 0, 1, 0}}));
}
}