[BOJ-Code] 1743 - 음식물 피하기

Posted by DHniyeo Blog on March 9, 2024

문제 링크

💡 너비 우선 탐색/깊이 우선 탐색/그래프 이론/그래프 탐색

Memory 1340KB Time 0ms Code Length 1483B

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include <stdio.h>
#include <queue>
#include <algorithm>

using namespace std;
int visited[100][100] = { 0 };
int n, m, k;
int map[100][101] = {0};
int dy[] = { -1,1,0,0 };
int dx[] = { 0,0,-1,1 };
struct info {
	int y;
	int x;
	int cnt;
};


int bfs(int y, int x) {
	visited[y][x] = 1;
	queue<info> q;
	q.push({ y,x,1 });

	int cnt = 0;
	while (!q.empty()) {
		info loc = q.front(); q.pop();
		cnt ++;
		for (int i = 0; i < 4; i++) {
			int ny = loc.y + dy[i];
			int nx = loc.x + dx[i];
			if (ny >= n || nx >= m || ny < 0 || nx < 0) continue;
			if (visited[ny][nx] == 1) continue;
			if (map[ny][nx] == 0) continue;
			visited[ny][nx] = 1;
			q.push({ ny,nx, loc.cnt + 1 });
		}
	}
	return cnt;
}
int dfs(int y, int x, int cnt) {
	visited[y][x] = 1;

	for (int i = 0; i < 4; i++) {
		int ny = y + dy[i];
		int nx = x + dx[i];
		if (ny >= n || nx >= m || ny < 0 || nx < 0) continue;
		if (visited[ny][nx] == 1) continue;
		if (map[ny][nx] == 0) continue;
		cnt = dfs(ny, nx, cnt + 1);
	}
	return cnt;
}

int main()
{

	scanf("%d %d %d", &n, &m, &k);
	getchar();
	
	for (int i = 0; i < k; i++) {
		int y, x;
		scanf("%d %d",&y, &x);
		getchar();
		map[y-1][x-1] = 1; // 음식물 쓰레기 위치
	}

	int max = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			if (visited[i][j] == 1) continue;
			if (map[i][j] == 0) continue;
			//int result = bfs(i,j);
			int result = dfs(i,j,1);
			if (result > max) {
				max = result;
			}
		}
	}
	printf("%d\n", max);

}

이 코드는 음식물 쓰레기가 떨어진 곳의 위치를 입력받아서, 해당 위치들을 연결된 쓰레기물끼리 묶어서 가장 큰 쓰레기물 덩어리의 크기를 찾는 프로그램이다.

입력된 위치들을 map 배열에 표시하고, 해당 위치를 방문했는지 여부를 visited 배열에 저장한다.

dfs 함수를 통해 각 위치에서 상하좌우로 이동하면서 연결된 쓰레기물을 찾고, 그 크기를 반환한다.

모든 위치를 탐색하면서 방문하지 않은 쓰레기물 위치를 찾아서 가장 큰 쓰레기물 덩어리의 크기를 찾는다.

가장 큰 쓰레기물 덩어리의 크기를 출력한다.