1
+ package _2020_카카오_인턴십 .P4 ;
2
+
3
+ public class Main {
4
+
5
+ public static void main (String [] args ) {
6
+ Solution sol = new Solution ();
7
+ System .out .println (sol .solution (new int [][]{{0 ,0 ,0 },{0 ,0 ,0 },{0 ,0 ,0 }}));
8
+ System .out .println (sol .solution (new int [][]{{0 ,0 ,0 ,0 ,0 ,0 ,0 ,1 },{0 ,0 ,0 ,0 ,0 ,0 ,0 ,0 },{0 ,0 ,0 ,0 ,0 ,1 ,0 ,0 },{0 ,0 ,0 ,0 ,1 ,0 ,0 ,0 },{0 ,0 ,0 ,1 ,0 ,0 ,0 ,1 },{0 ,0 ,1 ,0 ,0 ,0 ,1 ,0 },{0 ,1 ,0 ,0 ,0 ,1 ,0 ,0 },{1 ,0 ,0 ,0 ,0 ,0 ,0 ,0 }}));
9
+ System .out .println (sol .solution (new int [][]{{0 ,0 ,1 ,0 },{0 ,0 ,0 ,0 },{0 ,1 ,0 ,1 },{1 ,0 ,0 ,0 }}));
10
+ System .out .println (sol .solution (new int [][]{{0 ,0 ,0 ,0 ,0 ,0 },{0 ,1 ,1 ,1 ,1 ,0 },{0 ,0 ,1 ,0 ,0 ,0 },{1 ,0 ,0 ,1 ,0 ,1 },{0 ,1 ,0 ,0 ,0 ,1 },{0 ,0 ,0 ,0 ,0 ,0 }}));
11
+ }
12
+ }
13
+
14
+ class Solution {
15
+
16
+ int N ;
17
+ int [] di = {-1 , 0 , 1 , 0 }, dj = {0 , 1 , 0 , -1 };
18
+ int [][] board , dp ;
19
+
20
+ public int solution (int [][] board ) {
21
+
22
+ N = board .length ;
23
+ this .board = board ;
24
+ dp = new int [N ][N ];
25
+
26
+ for (int i = 0 ; i < N ; i ++) {
27
+ for (int j = 0 ; j < N ; j ++) {
28
+ dp [i ][j ] = Integer .MAX_VALUE ;
29
+ }
30
+ }
31
+
32
+ dp [0 ][0 ] = 0 ;
33
+ for (int d = 1 ; d <= 2 ; d ++) dfs (0 , 0 , d );
34
+
35
+ // for (int i = 0; i < N; i++) {
36
+ // for (int j = 0; j < N; j++) {
37
+ // if (dp[i][j] == Integer.MAX_VALUE) System.out.print("INF ");
38
+ // else System.out.print(dp[i][j] + " ");
39
+ // }
40
+ // System.out.println();
41
+ // }
42
+
43
+ return dp [N -1 ][N -1 ];
44
+ }
45
+
46
+ void dfs (int i , int j , int d ) {
47
+ if (i == N -1 && j == N -1 ) return ;
48
+
49
+ for (int k = 0 ; k < 4 ; k ++) {
50
+ int to_i = i + di [k ];
51
+ int to_j = j + dj [k ];
52
+
53
+ int plus = d == k ? 100 : 600 ;
54
+ if (isValidPath (to_i , to_j ) && board [to_i ][to_j ] == 0 && dp [to_i ][to_j ] >= dp [i ][j ]+plus ) {
55
+ // System.out.println(i + " " + j + " | to: " + to_i + " " + to_j + " | d : " + d + " k : " + k + " | cost : " + (dp[i][j]+plus));
56
+ dp [to_i ][to_j ] = dp [i ][j ]+plus ;
57
+ dfs (to_i , to_j , k );
58
+ }
59
+ }
60
+ }
61
+
62
+ boolean isValidPath (int i , int j ) {
63
+ return 0 <= i && i < N && 0 <= j && j < N ;
64
+ }
65
+ }
0 commit comments