[백준/C++] 7576번 토마토

2021. 3. 25. 19:30알고리즘/BFS DFS

728x90
반응형

문제: www.acmicpc.net/problem/7576

 

7576번: 토마토

첫 줄에는 상자의 크기를 나타내는 두 정수 M,N이 주어진다. M은 상자의 가로 칸의 수, N은 상자의 세로 칸의 수를 나타낸다. 단, 2 ≤ M,N ≤ 1,000 이다. 둘째 줄부터는 하나의 상자에 저장된 토마토

www.acmicpc.net

 

 

문제풀이

 

BFS를 이용해 최단거리를 구하는 문제이다.

 

이 문제는 시작점(익은 토마토)이 여러 곳이므로 시작점을 모두 큐에 넣어준다.

 

 

코드

#include <iostream>
#include <queue>

using namespace std;

int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};
int board[1000][1000];
int dist[1000][1000];

int main(){
    ios::sync_with_stdio(false); cin.tie(NULL);

    int m,n;
    cin>>m>>n;

    queue<pair<int,int>> q;
    for(int i=0; i<n; i++){ //입력
        for(int j=0; j<m; j++){
            cin>>board[i][j];

            if(board[i][j] == 1) //시작점(익은 토마토)이므로 큐에 푸시
                q.push({i,j});

            if(board[i][j] == 0) //익지 않은 토마토는 -1
                dist[i][j] = -1;
        }
    }
    //빈 공간의 dist값은 모두 0이다. (전역으로 선언)

    while(!q.empty()){
        pair<int,int> cur = q.front();
        q.pop();

        for(int dir=0; dir<4; dir++){
            int nx = cur.first + dx[dir];
            int ny = cur.second + dy[dir];

            if(nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
            if(dist[nx][ny] >= 0) continue;

            dist[nx][ny] = dist[cur.first][cur.second] + 1;
            q.push({nx,ny});
        }

    }

    int day=0;
    for(int i=0; i<n; i++){
        for(int j=0; j<m; j++){
            if(dist[i][j] == -1){ //익지 않은 토마토가 있다면 -1 출력
                cout<<-1;
                return 0;
            }
            day = max(day, dist[i][j]); 
            //dist의 값 중 가장 큰 값이 토마토가 모두 익는데 걸린 일수이다.
        }
    }

    cout<<day;

    return 0;
}

 

 

결과

 

 

 

728x90
반응형

'알고리즘 > BFS DFS' 카테고리의 다른 글

[백준/C++] 4179번 불!  (0) 2021.03.26
[백준/C++] 1697번 숨바꼭질  (0) 2021.03.26
[백준/C++] 2178번 미로 탐색  (0) 2021.03.25
[백준/C++] 1926번 그림  (0) 2021.03.24
[백준/C++] 11724번 연결 요소의 개수  (0) 2021.02.25