๐Ÿ’  BOJ/Class 3

[BOJ][C++] ๋ฐฑ์ค€ 14940๋ฒˆ: ์‰ฌ์šด ์ตœ๋‹จ๊ฑฐ๋ฆฌ (Silver I)

์„ ๋‹ฌ 2024. 11. 2. 02:23
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

์ง€๋„๊ฐ€ ์ฃผ์–ด์ง€๋ฉด ๋ชจ๋“  ์ง€์ ์— ๋Œ€ํ•ด์„œ ๋ชฉํ‘œ์ง€์ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜์—ฌ๋ผ.
๋ฌธ์ œ๋ฅผ ์‰ฝ๊ฒŒ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ์˜ค์ง ๊ฐ€๋กœ์™€ ์„ธ๋กœ๋กœ๋งŒ ์›€์ง์ผ ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ•˜์ž.

์ž…๋ ฅ

์ง€๋„์˜ ํฌ๊ธฐ n๊ณผ m์ด ์ฃผ์–ด์ง„๋‹ค. n์€ ์„ธ๋กœ์˜ ํฌ๊ธฐ, m์€ ๊ฐ€๋กœ์˜ ํฌ๊ธฐ๋‹ค.(2 ≤ n ≤ 1000, 2 ≤ m ≤ 1000)
๋‹ค์Œ n๊ฐœ์˜ ์ค„์— m๊ฐœ์˜ ์ˆซ์ž๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. 0์€ ๊ฐˆ ์ˆ˜ ์—†๋Š” ๋•…์ด๊ณ  1์€ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋•…, 2๋Š” ๋ชฉํ‘œ์ง€์ ์ด๋‹ค. ์ž…๋ ฅ์—์„œ 2๋Š” ๋‹จ ํ•œ๊ฐœ์ด๋‹ค.

์ถœ๋ ฅ

๊ฐ ์ง€์ ์—์„œ ๋ชฉํ‘œ์ง€์ ๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ์›๋ž˜ ๊ฐˆ ์ˆ˜ ์—†๋Š” ๋•…์ธ ์œ„์น˜๋Š” 0์„ ์ถœ๋ ฅํ•˜๊ณ , ์›๋ž˜ ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋•…์ธ ๋ถ€๋ถ„ ์ค‘์—์„œ ๋„๋‹ฌํ•  ์ˆ˜ ์—†๋Š” ์œ„์น˜๋Š” -1์„ ์ถœ๋ ฅํ•œ๋‹ค.

 

ํ’€์ด

// ํ’€์ด : https://whkakrkr.tistory.com

#include <iostream>
#include <vector>
#include <queue>

using namespace std;

typedef pair<int, int> ci;

int dx[] = {1,-1,0,0};
int dy[] = {0,0,1,-1};

int main() {
    // input
    int n,m;
    cin >> n >> m;
    vector<vector<int>>board(n, vector<int>(m));
    int start_x, start_y;
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cin >> board[i][j];
            
            if(board[i][j]==2) {
                start_x = i;
                start_y = j;
            }
        }
    }
    
    // solution : bfs
    vector<vector<int>>dist(n, vector<int>(m, -1));
    queue<ci>q;
    
    dist[start_x][start_y] = 0;
    q.push({start_x, start_y});
                
    while(!q.empty()) {
        ci cur = q.front();
        q.pop();
        int d = dist[cur.first][cur.second]; 
        
        for(int dir=0; dir<4; dir++) {
            int x = cur.first + dx[dir];
            int y = cur.second + dy[dir];
            
            if(x<0 || x>=n || y<0 || y>=m) { 
                // out of boundary
                continue;
            }
            
            if(dist[x][y]!=-1 || board[x][y]==0) { 
                // already visit or can't visit
                continue;
            }
            
            dist[x][y] = d+1;
            q.push({x,y});
        }
    }
    
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            if(board[i][j]==0) {
                dist[i][j] = 0;
            }
        }
    }
    
    // output
    for(int i=0; i<n; i++) {
        for(int j=0; j<m; j++) {
            cout << dist[i][j] << " ";
        }
        cout << "\n";
    }
    
    return 0;
}
๋ฐ˜์‘ํ˜•