๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 14923๋ฒˆ - ๋ฏธ๋กœ ํƒˆ์ถœ

by dkswnkk 2021. 11. 14.

๋ฌธ์ œ

 

14923๋ฒˆ: ๋ฏธ๋กœ ํƒˆ์ถœ

ํ™์ต์ด๋Š” ์‚ฌ์•…ํ•œ ๋งˆ๋ฒ•์‚ฌ์˜ ๊พ์— ์†์•„ N x M ๋ฏธ๋กœ (Hx, Hy) ์œ„์น˜์— ๋–จ์–ด์กŒ๋‹ค. ๋‹คํ–‰ํžˆ๋„ ํ™์ต์ด๋Š” ๋งˆ๋ฒ•์‚ฌ๊ฐ€ ๋งŒ๋“  ๋ฏธ๋กœ์˜ ํƒˆ์ถœ ์œ„์น˜(Ex, Ey)๋ฅผ ์•Œ๊ณ  ์žˆ๋‹ค. ํ•˜์ง€๋งŒ ๋ฏธ๋กœ์—๋Š” ๊ณณ๊ณณ์— ๋งˆ๋ฒ•์‚ฌ๊ฐ€ ์„ค์น˜ํ•œ ๋ฒฝ์ด

www.acmicpc.net

 

์ฝ”๋“œ

#include <iostream>
#include <queue>
using namespace std;

int N,M,start_x,start_y,arrived_x,arrived_y,ans;
int map[1001][1001];
int visited[1001][1001][2];
const int dx[4]={0,0,-1,1};
const int dy[4]={-1,1,0,0};

int bfs(int x,int y){
    queue<pair<int,pair<int,int>>>q;    //{๋ฒฝ ๋šซ๊ธฐ ์—ฌ๋ถ€,{x,y}}
    q.push({1,{x,y}});  //๋ฒฝ์„ ๋šซ์„ ์ˆ˜ ์žˆ์œผ๋ฉด 1
    visited[x][y][1]=1;

    while(!q.empty()){
        int wand=q.front().first;
        int x=q.front().second.first;
        int y=q.front().second.second;
        if(x==arrived_x-1&&y==arrived_y-1){ //๋„์ฐฉํ–ˆ์„ ๋•Œ ์ข…๋ฃŒ
            return visited[x][y][wand];
        }
        q.pop();
        for(int i=0; i<4; i++){
            int nx=x+dx[i];
            int ny=y+dy[i];
            if(nx>=0&&nx<N&&ny>=0&&ny<M){   //๋ฒฝ์˜ ๋ฒ”์œ„๋ฅผ ๋ฒ—์–ด๋‚˜์ง€ ์•Š์•˜์„ ๋•Œ
                if(map[nx][ny]==1&&wand){   //๋ฒฝ์ด ์žˆ๊ณ , ์ง€ํŒก์ด๋ฅผ ์‚ฌ์šฉ ํ•  ์ˆ˜ ์žˆ์„ ๋•Œ
                    visited[nx][ny][wand-1] = visited[x][y][wand]+1;    //๋ฒฝ์„ ๋šซ๊ณ  ์ด์ „ ์ตœ๋‹จ๊ฑฐ๋ฆฌ์— +1 ํ•ด์ค€๋‹ค.
                    q.push({wand-1,{nx,ny}});
                }
                else if(map[nx][ny]==0&&!visited[nx][ny][wand]){    //๋ฒฝ์ด ์—†๊ณ , ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๋˜ ๊ณณ์ผ๊ฒฝ์šฐ
                    visited[nx][ny][wand]=visited[x][y][wand]+1;
                    q.push({wand,{nx,ny}});

                }

            }
        }
    }
    return -1;
}

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);

    cin>>N>>M>>start_x>>start_y>>arrived_x>>arrived_y;

    for(int i=0; i<N; i++){
        for(int k=0; k<M; k++){
            cin>>map[i][k];
        }
    }

    ans=bfs(start_x-1,start_y-1);
    if(ans==-1) cout<<-1;
    else cout<<ans-1;

}

๋Œ“๊ธ€