ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 벽 부수고 이동하기
    백준알고리즘 2019. 10. 12. 20:14

    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
    65
    66
    67
    68
    #include<iostream>
    #include<queue>
    #include<utility>
     
     
    using namespace std;
     
    int r,c;
    string map[1000];
    int dist[1000][1000][2];
    bool d[1000][1000][2];
    int dx[] ={0,0,1,-1};
    int dy[] = {1,-1,0,0};
     
    void bfs(){
        queue<pair<pair<int,int>,int>> q;
        q.push({{0,0},0});
        d[0][0][0= true;
        dist[0][0][0= 1;
        while(!q.empty()){
            int x = q.front().first.first;int y = q.front().first.second;
            int cnt = q.front().second;
            q.pop();
            for(int i = 0; i < 4; i++){
                int nx = x+dx[i]; int ny = y+dy[i];
                if(nx <0 || nx>= r|| ny<0 ||ny>=c) continue;
                if(d[nx][ny][cnt] == truecontinue;
                if(map[nx][ny]== '0' ){
                    d[nx][ny][cnt] = true;
                    dist[nx][ny][cnt] = dist[x][y][cnt]+1;
                    q.push({{nx,ny},cnt});
                }
                if(map[nx][ny] == '1' && cnt == 0){
                    d[nx][ny][cnt] = true;
                    dist[nx][ny][cnt+1= dist[x][y][cnt]+1;
                    q.push({{nx,ny},cnt+1});
                }
            }
        }
    }
     
    int main(){
        ios_base::sync_with_stdio(0);
        cin.tie(0);
     
        cin>>r>>c;
     
        for(int i = 0; i< r; i++){
            cin>>map[i];
        }
        bfs();
        int s = 0,z =0;
        if(dist[r-1][c-1][0== 0)
            s = 987654321;
        else s = dist[r-1][c-1][0];
        if(dist[r-1][c-1][1== 0)
            z = 987654321;
        else z = dist[r-1][c-1][1];
        if( s > z)
            s = z;
     
        
        if(s == 987654321)
            cout<<-1<<'\n';
        else
            cout<<s<<'\n';
        return 0;
    }
    http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
     

    DP냄새가 나는 BFS였다 

    단 한번만 뚫을수있다는점을 생각하면 그다지어렵지는않은문제

    '백준알고리즘' 카테고리의 다른 글

    구슬 탈출2  (0) 2019.10.14
    말이 되고픈 원숭이  (0) 2019.10.14
    과외맨  (0) 2019.10.10
    N-Queen  (0) 2019.10.09
    진우의 달 여행(Large)  (0) 2019.10.09

    댓글

Designed by Tistory.