[백준] 7576번: 토마토(C++)

2025. 5. 24. 15:44·개발/알고리즘

문제 링크

https://www.acmicpc.net/problem/7576

 

 

코드 구현

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

using namespace std;

vector<vector<int>> box;
int days[1000][1000];
queue<pair<int, int>> q;

vector<pair<int, int>> dir = { {0, -1}, {0, 1}, {-1, 0}, {1, 0} };

bool IsValid(int x, int y)
{
	if (x >= 0 && x < box[0].size() && y >= 0 && y < box.size())
	{
		return true;
	}

	return false;
}

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

		for (int i = 0; i < 4; i++)
		{
			int x = now.first + dir[i].first;
			int y = now.second + dir[i].second;

			// 범위 안에 있고 익지 않았으면 익은 토마토로
			if (IsValid(x, y) && box[y][x] == 0)
			{
				box[y][x] = 1;
				q.push(make_pair(x, y));
				days[y][x] = days[now.second][now.first] + 1;
			}
		}
	}


}

int main()
{
	int m, n;
	cin >> m >> n;

	box.resize(n);

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			int t;
			cin >> t;
			box[i].push_back(t);

			// 처음부터 익어있는 토마토 큐에 삽입
			if (t == 1) q.push(make_pair(j, i));
		}
	}

	bfs();

	int result = 0;

	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (box[i][j] == 0)
			{
				cout << -1;
				return 0;
			}

			result = max(result, days[i][j]);
		}
	}
	
	cout << result;

	return 0;
}

 

 

해결 방법

  • bfs를 이용하여 해결
  • 토마토가 담긴 박스를 2차원 벡터로 구현
  • 익어 있는 (1) 토마토를 우선적으로 큐에다 삽입
  • 상하좌우를 체크하면서 bfs 순환 -> 익지 않은 토마토는 익은 토마토로 변경 후 큐에 삽입
  • days 배열에 날짜 +1을 하며 순회를 마쳤을 때 최대값을 출력

'개발 > 알고리즘' 카테고리의 다른 글

[프로그래머스] 단어 변환(C++)  (1) 2025.05.26
[백준] 1967번: 트리의 지름(C++)  (1) 2025.05.16
[프로그래머스] 가장 먼 노드(C++)  (1) 2025.05.15
[프로그래머스] 길 찾기 게임(C++)  (2) 2025.05.13
[백준] 회의실 배정(C++)  (1) 2025.05.12
'개발/알고리즘' 카테고리의 다른 글
  • [프로그래머스] 단어 변환(C++)
  • [백준] 1967번: 트리의 지름(C++)
  • [프로그래머스] 가장 먼 노드(C++)
  • [프로그래머스] 길 찾기 게임(C++)
Majangnan
Majangnan
  • Majangnan
    개발 모코코
    Majangnan
  • 전체
    오늘
    어제
    • 분류 전체보기 (63) N
      • 개발 (62) N
        • C# (10)
        • SQL (3)
        • Unity (8)
        • Unreal (10)
        • C++ (2)
        • Server (1)
        • DX11 (8)
        • 알고리즘 (19) N
  • 블로그 메뉴

    • 홈
    • 방명록
    • 깃허브
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    MAC
    Unity
    UnReal
    프로그래머스
    상속
    코딩테스트
    sql
    슈팅게임
    3dlight
    블루프린트
    언리얼
    DX11
    알고리즘
    blueprint
    백준
    dx3d
    DirectX11
    c++
    Mecanim
    C#
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
Majangnan
[백준] 7576번: 토마토(C++)
상단으로

티스토리툴바