File tree Expand file tree Collapse file tree 5 files changed +79
-0
lines changed
Expand file tree Collapse file tree 5 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ //최단거리
2+
3+ #include <stdio.h>
4+ #include <string.h>
5+ int INF = 10000 ;
6+
7+
8+ int M ,N ;
9+
10+ int dx [4 ] = {1 ,-1 ,0 ,0 };
11+ int dy [4 ] = {0 ,0 ,1 ,-1 };
12+
13+ void dijkstra (int maze [][M + 1 ],int answer [][M + 1 ]){
14+ int front = 0 , rear = 0 ;
15+ int q [M * N * 4 ][2 ];
16+ q [front ][0 ] = 1 ;
17+ q [front ][1 ] = 1 ;
18+ rear ++ ;
19+ answer [1 ][1 ] = 0 ; // 초기 거리값 = 0
20+
21+ while (front < rear )
22+ {
23+ int cx = q [front ][0 ];
24+ int cy = q [front ][1 ];
25+ front ++ ;
26+
27+ for (int i = 0 ; i < 4 ; i ++ )
28+ {
29+ int nx = cx + dx [i ];
30+ int ny = cy + dy [i ];
31+
32+ if (nx < 1 || nx > N || ny < 1 || ny > M )
33+ continue ;
34+ if (maze [nx ][ny ] == 1 ) //벽을 지날때
35+ {
36+ if (answer [nx ][ny ] > answer [cx ][cy ] + 1 )
37+ {
38+ answer [nx ][ny ] = answer [cx ][cy ] + 1 ;
39+ q [rear ][0 ] = nx ; // 이 시점에서 rear == front !!
40+ q [rear ][1 ] = ny ;
41+ rear ++ ;
42+ }
43+ }
44+ else if (maze [nx ][ny ] == 0 )
45+ {
46+ if (answer [nx ][ny ] > answer [cx ][cy ]) //빈 방을 지날 때
47+ {
48+ answer [nx ][ny ] = answer [cx ][cy ];
49+ q [rear ][0 ] = nx ;
50+ q [rear ][1 ] = ny ;
51+ rear ++ ;
52+ }
53+ }
54+ }
55+ }
56+ }
57+
58+ int main (){
59+ scanf ("%d%2d" ,& M ,& N );
60+ int maze [N + 1 ][M + 1 ];
61+ int answer [N + 1 ][M + 1 ];
62+
63+
64+ for (int i = 1 ; i <= N ; i ++ )
65+ {
66+ getchar ();
67+ for (int j = 1 ; j <= M ; j ++ )
68+ {
69+ scanf ("%1d" ,& maze [i ][j ]);
70+ answer [i ][j ] = INF ;
71+ }
72+ }
73+
74+ dijkstra (maze ,answer );
75+
76+ printf ("\n%d" ,answer [N ][M ]);
77+
78+ return 0 ;
79+ }
You can’t perform that action at this time.
0 commit comments