https://www.acmicpc.net/problem/13700



BFS를 이용하여 이동 회수를 최소로 하는 문제로

이전에 게시한 1697번 숨바꼭질 문제와 거의 유사한 문제이다.



visited 배열을 이용하여 이전에 방문을 한적이 없을 때만 다음 좌표로 이동하도록 큐에 담았으며

경찰서의 위치를 -1로 표시하여 이동할 수 없도록 했다.


이동 회수가 적은 순서대로 큐에 담아지기 때문에

큐에 담긴 위치가 빈털털이의 집이라면 이동회수는 최소가 되어 바로 답을 출력하면 된다.



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
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
 
int main() {
    
    int ans=-1;
    int N,S,D,F,B,K;
    cin>>N>>S>>D>>F>>B>>K;
    
    int k;
    vector<int> visited(N+1,0);
    for(int i=0;i<K;i++){
        cin>>k;
        visited[k]=-1//경찰서 위치
    }
    
    queue<pair<int,int>> q;
    q.push(make_pair(S,0));
    while(!q.empty()){
        int location=q.front().first;
        int cnt=q.front().second;
        q.pop();
        
        if(location==D){
            ans=cnt;
            break;
        }
        
        if(location+F<=&& visited[location+F]==0){
            visited[location+F]++;
            q.push(make_pair(location+F,cnt+1));
        }
        
        if(location-B>=1 && visited[location-B]==0){
            visited[location-B]++;
            q.push(make_pair(location-B,cnt+1));
        }
    }
    
    if(ans==-1cout<<"BUG FOUND"<<endl;
    else    cout<<ans<<endl;
    
    return 0;
}
 
cs


'알고리즘(BOJ) > BFS' 카테고리의 다른 글

백준 12869번 - 뮤탈리스크  (0) 2019.08.18
백준 15558번 - 점프 게임  (0) 2019.07.29
백준 1260번 - DFS와 BFS  (0) 2019.04.11
백준 1963번 - 소수 경로  (0) 2018.03.28
백준 5014번 - 스타트링크  (0) 2018.02.11

+ Recent posts