View

반응형

 

알고리즘 분류: 그래프 이론, 그래프 탐색, 너비 우선 탐색

문제 링크: https://www.acmicpc.net/problem/7576

 

7576번: 토마토

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

www.acmicpc.net

 

 

 

 

【 풀이 】

 

이 문제는 시작점이 여러 개로 주어질 수 있기 때문에, 여러 정점에서 동시에 출발할 수 있도록 해주어야 한다.

모든 시작점(1) 들을 큐에 밀어 넣어서, bfs를 정점들마다 번갈아가면서 탐색할 수 있게끔 해주면 된다.

 

그리고 날짜를 기록하는 게 곧 탐색의 거리를 의미하기도 하기에

배열마다 거리를 계산해서 그 최댓값을 출력해 보았다.

 

배열 값이 모두 0인 경우 (이걸 모르고 있었어서 헤맸다)

배열 값이 모두 차있는 경우 (0이 없는 경우)

정도만 주의하면 될 것 같다.

 

 

【 코드 】

 

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

int front_y[4] = { -1,1,0,0 };
int front_x[4] = { 0,0,-1,1 };

queue<pair<int, int>>pos;
int tomato[1001][1001];
int dist[1001][1001];
int visited[1001][1001];
int m, n;

// 시작해야하는 정점(vertex)들을 큐에 넣어주는 함수
// bfs 를 각 정점들마다 번갈아가면서 하게 만들어 줌.
void vertex(int y, int x) {
	pos.push(make_pair(y, x));
}

void bfs(int here_y, int here_x) {
	visited[here_y][here_x] = true;
	pos.push(make_pair(here_y, here_x));
	dist[here_y][here_x] = 0;

	while (pos.empty() == false) {
		if (!visited[here_y][here_x])
			visited[here_y][here_x] = true;
		here_y = pos.front().first;
		here_x = pos.front().second;
		pos.pop();

		for (int dir = 0; dir < 4; dir++) {
			int next_y = here_y + front_y[dir];
			int next_x = here_x + front_x[dir];

			if (next_y < 0 || next_x < 0)	continue;
			if (next_y >= n || next_x >= m)	continue;
			if (tomato[next_y][next_x] == -1)continue;			
			if (tomato[next_y][next_x] == 1)continue;
			if (visited[next_y][next_x])	continue;

			visited[next_y][next_x] = true;
			pos.push(make_pair(next_y, next_x));
			dist[next_y][next_x] = dist[here_y][here_x] + 1;
			tomato[next_y][next_x] = 1;
		}
	}
}

int main() {
	bool isPossible = false;
	bool isZero = true;
	int i, j;
	cin >> m >> n;

	for (i = 0; i < n; i++)
		for (j = 0; j < m; j++) {
			cin >> tomato[i][j];
			if (tomato[i][j] != 0)	isZero = false;
			if (tomato[i][j] == -1) visited[i][j] = -1;
			if (tomato[i][j] == 1)	vertex(i, j);
		}
	
	if(!isZero)
		bfs(pos.front().first, pos.front().second);

	for (i = 0; i < n; i++) {
		for (j = 0; j < m; j++)
			if (visited[i][j] == 0) { isPossible = true; break; }
		if (isPossible) { cout << -1; break; }
	}

	if (!isPossible) {
		int max = 0;
		for (i = 0; i < n; i++) 
			for (j = 0; j < m; j++) 
				if (max < dist[i][j])
				max = dist[i][j];
		cout << max;
	}

	return 0;
}

 

728x90
반응형

'Problem Solving > Baekjoon' 카테고리의 다른 글

[백준] 28422: XOR 카드 게임  (0) 2024.04.08
[백준] 1149번: RGB거리 [C++]  (0) 2023.10.02
[백준] 1074번: Z [C++]  (0) 2023.09.30
[백준] 2630번: 색종이 만들기 [C++]  (0) 2023.09.29
[백준] 1697번: 숨바꼭질 [C++]  (0) 2023.09.28
Share Link
reply
250x250
반응형
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31