1
+ import java .io .BufferedReader ;
2
+ import java .io .InputStreamReader ;
3
+ import java .util .ArrayDeque ;
4
+ import java .util .Deque ;
5
+ import java .util .PriorityQueue ;
6
+ import java .util .StringTokenizer ;
7
+
8
+ public class JW_전투_로봇 {
9
+
10
+ static int n ;
11
+ static int [][] board ;
12
+ static int [] dy = { -1 , 1 , 0 , 0 };
13
+ static int [] dx = { 0 , 0 , -1 , 1 };
14
+ static int level = 2 , count = 0 , totalMove = 0 ;
15
+
16
+ public static void main (String [] args ) throws Exception {
17
+ BufferedReader br = new BufferedReader (new InputStreamReader (System .in ));
18
+ n = Integer .parseInt (br .readLine ());
19
+ board = new int [n ][n ];
20
+ int sy = 0 , sx = 0 ;
21
+ for (int i = 0 ; i < n ; i ++) {
22
+ StringTokenizer st = new StringTokenizer (br .readLine ());
23
+ for (int j = 0 ; j < n ; j ++) {
24
+ int p = Integer .parseInt (st .nextToken ());
25
+ // 초기 로봇 위치 저장
26
+ if (p == 9 ) {
27
+ sy = i ;
28
+ sx = j ;
29
+ } else if (p != 0 ) {
30
+ board [i ][j ] = p ;
31
+ }
32
+ }
33
+ }
34
+ Deque <int []> dq = new ArrayDeque <>();
35
+ boolean [][] visited = new boolean [n ][n ];
36
+ dq .offer (new int [] { 0 , sy , sx });
37
+ // BFS
38
+ while (!dq .isEmpty ()) {
39
+ // 처리할 수 있는 몬스터들의 위치에 따라 우선 순위 부여
40
+ PriorityQueue <int []> pq = new PriorityQueue <>((o1 , o2 ) -> o1 [0 ] != o2 [0 ] ? o1 [0 ] - o2 [0 ] : o1 [1 ] - o2 [1 ]);
41
+ // 깊이 별로 BFS 진행
42
+ int t = dq .size ();
43
+ while (t -- > 0 ) {
44
+ int [] cur = dq .poll ();
45
+ int y = cur [1 ], x = cur [2 ];
46
+ if (visited [y ][x ])
47
+ continue ;
48
+ visited [y ][x ] = true ;
49
+ // 해당 레벨에서 잡을 수 있는 몬스터가 존재한다면 우선 순위 큐에 저장
50
+ if (isCatch (y , x )) {
51
+ pq .offer (cur );
52
+ continue ;
53
+ }
54
+ for (int i = 0 ; i < 4 ; i ++) {
55
+ int ny = y + dy [i ], nx = x + dx [i ];
56
+ if (isValid (ny , nx ) && !visited [ny ][nx ]) {
57
+ dq .offer (new int [] { cur [0 ] + 1 , ny , nx });
58
+ }
59
+ }
60
+ }
61
+ // 해당 깊이에서 처리할 수 있는 몬스터를 1개 이상 발견했다면
62
+ if (!pq .isEmpty ()) {
63
+ // 우선 순위가 가장 높은 몬스터를 처리
64
+ int [] cur = pq .poll ();
65
+ totalMove += cur [0 ];
66
+ int y = cur [1 ], x = cur [2 ];
67
+ board [y ][x ] = 0 ;
68
+ // 없앤 몬스터의 수 갱신과 레벨 업
69
+ count ++;
70
+ if (count == level ) {
71
+ level ++;
72
+ count = 0 ;
73
+ }
74
+ // 큐를 비우고 해당 위치에서 다시 시작
75
+ dq .clear ();
76
+ dq .offer (new int [] { 0 , y , x });
77
+ visited = new boolean [n ][n ];
78
+ }
79
+ }
80
+ System .out .println (totalMove );
81
+ }
82
+
83
+ // 몬스터를 없앨 수 있는지 확인하는 함수
84
+ private static boolean isCatch (int y , int x ) {
85
+ return 0 < board [y ][x ] && board [y ][x ] < level ;
86
+ }
87
+
88
+ // 경계 체크 함수
89
+ private static boolean isValid (int y , int x ) {
90
+ return 0 <= y && y < n && 0 <= x && x < n && board [y ][x ] <= level ;
91
+ }
92
+ }
0 commit comments