출처 : 2011 교원프로그래밍경진대회
알고리즘 : BFS
조건 하나가 더 추가된 BFS 문제이다. 재귀함수로 풀려고 하면 DFS가 되어 버리니 조심해야한다.
특정 위치에서 상하좌우를 확인해야 하므로 dir(방향배열)을 통해 간단하게 처리했다.
BFS의 장점은 가장 먼저 목표에 도달한 시행에서의 값이 답이 된다는 것이다.
따라서 목표에 도달했을 때 반복문을 탈출하여 출력하면 된다.
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
|
#include<iostream>
#include<cmath>
#include<queue>
using namespace std;
int in[1002][1002];
int dir[4][2]={{0,1}, {0,-1}, {1,0}, {-1,0}};
int check[1002][1002];
typedef struct dot{
int a,b,ans;
}dot;
queue<dot> q;
int main(){
int ans=9999999;
int n,m, flag=0;
cin>>n>>m;
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
cin>>in[i][j];
}
}
check[1][1]=1;
dot first={1,1,1};
q.push(first);
while(!q.empty()){
int a=q.front().a,b=q.front().b,tmp=q.front().ans;
q.pop();
if(a==n&&b==m){
ans=tmp;
break;
}
for(int i=0;i<4;i++){
int na=a+dir[i][0],nb=b+dir[i][1];
if( check[na][nb] || !in[na][nb] || abs(in[na][nb]-in[a][b])>1 )
continue;
dot temp={na,nb,tmp+1};
q.push(temp);
check[na][nb]=1;
}
}
if(ans!=9999999)
cout<<ans;
else
cout<<"0";
}
|
[백준] 2583번 영역 구하기 (C) (0) | 2020.03.14 |
---|---|
[코드업] 3500 : 지뢰 찾기 2 (C) (0) | 2020.03.13 |
[백준] 2667번 단지 번호 붙이기 (C) (0) | 2020.03.10 |
[백준] 2606번 바이러스 (C) (0) | 2020.03.10 |
[코드업] 3212 : 위상 정렬(topological sort) (C) (0) | 2020.03.09 |