[백준] 7576번 토마토

2025. 1. 11. 22:40·백준 문제/BFS

문제: 7576번: 토마토

basic-algo-lecture/workbook/0x09.md at master · encrypted-def/basic-algo-lecture

 

basic-algo-lecture/workbook/0x09.md at master · encrypted-def/basic-algo-lecture

바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.

github.com

 

#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
#include <iomanip> // setprecision을 사용하기 위한 헤더
#include <climits>
#include <list>

using namespace std;


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

    int m, n; // m: 가로, n: 세로
    cin >> m >> n; 

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

    vector<vector<int>> board(n);
    vector<vector<int>> visit(n);
    vector<vector<int>> dists(n);
    queue<pair<int, int>> nexts;

    int startCnt = 0;
    for (int i = 0; i < n; i++) {
        board[i] = vector<int>(m);
        visit[i] = vector<int>(m);
        dists[i] = vector<int>(m);

        for (int j = 0; j < m; j++) {
            cin >> board[i][j];

            if (board[i][j] == 1) {
                nexts.push(make_pair(i, j));
                visit[i][j] = 1;
                dists[i][j] = 0;

                startCnt++; // 이 값이 m*n 값과 같으면 0 출력, 0이면 -1 출력
            }
        }
    }

    if (startCnt == 0)
        cout << -1;
    else if (startCnt == m * n)
        cout << 0;
    else {
        while (!nexts.empty()) {
            pair<int, int> cur = nexts.front();
            nexts.pop();

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

                if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
                if (visit[nx][ny] == 1 || board[nx][ny] == -1) continue;

                board[nx][ny] = 1; // 토마토 익었다 ~_~
                dists[nx][ny] = dists[cur.first][cur.second] + 1;

                nexts.push(make_pair(nx, ny));
                visit[nx][ny] = 1;
            }
        }

        int max = -1;
        bool flag = false;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (board[i][j] == 0)
                    flag = true; // 익지 않은 토마토가 있어..

                if (max < dists[i][j])
                    max = dists[i][j];
            }
        }
        if (flag)
            cout << -1;
        else
            cout << max;
    }

    
    return 0;
}

 

그냥 BFS 를 살짝 응용하면 바로 풀리는 문제다. 출력은 가장 긴 dist 값을 출력해주면 된다. 이 문제는 2178번 미로탐색 문제 풀었으면 바로 쉽게 풀 수 있다.

 

 

 

참고자료:

BaaaaaaaarkingDog | [실전 알고리즘] 0x09강 - BFS

 

[실전 알고리즘] 0x09강 - BFS

안녕하세요 여러분, 드디어 올 것이 왔습니다. 마음의 준비를 단단히 하셔야 합니다.. 드디어 실전 알고리즘 강의에서 첫 번째 고비에 도달했는데 이 강의와 함께 이번 고비를 잘 헤쳐나가면 좋

blog.encrypted.gg

 

'백준 문제/BFS' 카테고리의 다른 글
  • [백준] 1697번 숨바꼭질
  • [백준] 4179번 불!
  • [백준] 2178번 미로 탐색
  • [백준] 1926번 그림
dubu0721
dubu0721
dubu0721 님의 블로그 입니다.
  • dubu0721
    dubu0721 님의 블로그
    dubu0721
  • 전체
    오늘
    어제
    • 분류 전체보기 (343) N
      • 프로그래밍언어론 정리 (5)
      • 컴퓨터네트워크 정리 (5)
      • 알고리즘&자료구조 공부 (64)
        • it 취업을 위한 알고리즘 문제풀이 입문 강의 (60)
        • 학교 알고리즘 수업 (3)
        • 실전프로젝트I (0)
      • 백준 문제 (196) N
        • 이분탐색 (7)
        • 투포인트 (10)
        • 그래프 (7)
        • 그리디 (24)
        • DP (25)
        • BFS (18) N
        • MST (7)
        • KMP (4)
        • Dijkstra (3)
        • Disjoints Set (4)
        • Bellman-Ford (2)
        • 시뮬레이션 (3)
        • 백트래킹 (15)
        • 위상정렬 (5)
        • 자료구조 (25)
        • 기하학 (1)
        • 정렬 (11)
        • 구현 (8)
        • 재귀 (8)
        • 수학 (8)
      • 유니티 공부 (11)
        • 레트로의 유니티 게임 프로그래밍 에센스 (11)
        • 유니티 스터디 자료 (0)
        • C# 공부 (0)
      • 유니티 프로젝트 (48)
        • 케이크게임 (13)
        • 점토게임 (35)
      • 언리얼 공부 (10)
        • 이득우의 언리얼 프로그래밍 (10)
      • 진로 (1)
      • 논문 읽기 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    스택
    시뮬레이션
    골드메탈
    우선순위큐
    dp
    백준
    BFS
    백트래킹
    해시
    자료구조
    유니티 프로젝트
    그리디
    C#
    바킹독
    수학
    레트로의 유니티 프로그래밍
    이벤트 트리거
    오블완
    그래프
    투포인터
    재귀
    유니티
    이득우
    큐
    정렬
    이분탐색
    유니티 공부 정리
    맵
    티스토리챌린지
    언리얼
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
dubu0721
[백준] 7576번 토마토
상단으로

티스토리툴바