[BOJ-Code] 1303 - 전쟁 - 전투

Posted by DHniyeo Blog on March 9, 2024

문제 링크

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

Memory 1276KB Time 0ms Code Length 1526B

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
81
82
#include <stdio.h>
#include <queue>
#include <algorithm>

using namespace std;



int n, m;
char map[101][101];
int visited[100][100] = { 0 };
int dy[] = { 0,0,-1,1 };
int dx[] = { -1,1,0,0 };
int dfs(int y, int x, char c, 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 >= m || nx >= n || ny < 0 || nx < 0) continue;
		if (visited[ny][nx] == 1) continue;
		if (map[ny][nx] != c) continue;
		cnt = dfs(ny, nx, c, cnt + 1);
	}
	return cnt;
}

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

	while (!q.empty()) {
		pair<int, int> tmp = q.front(); q.pop();
		
		for (int i = 0; i < 4; i++) {
			int ny = tmp.first + dy[i];
			int nx = tmp.second + dx[i];
			if (ny >= m || nx >= n || ny < 0 || nx < 0) continue;
			if (visited[ny][nx] == 1) continue;
			if (map[ny][nx] != c) continue;
			visited[ny][nx] = 1;
			q.push({ ny,nx });
			cnt++;
		}
	}
	return cnt;
}


int main()
{
	
	int w_result = 0;
	int b_result = 0;
	
	scanf("%d %d", &n, &m);
	getchar();
	for (int i = 0; i < m; i++) {
		scanf("%s", map[i]);
		getchar();
	}

	for (int i = 0; i < m; i++) {
		for (int j = 0; j < n; j++) {
			if (visited[i][j]) continue;
			//int sum = dfs(i, j, map[i][j], 1);
			int sum = bfs(i, j, map[i][j], 1);
			if (map[i][j] == 'W')
			{
				w_result = w_result + sum * sum;
			}
			else if (map[i][j] == 'B')
			{
				b_result = b_result + sum * sum;
			}
		}
	}
	printf("%d %d\n", w_result, b_result);


}

이 코드는 입력으로 주어지는 2차원 배열 지도에서 ‘W’와 ‘B’로 표시된 영역의 넓이를 구하는 프로그램이다.

  • dfs 함수는 깊이 우선 탐색을 이용하여 특정 좌표에서 상하좌우로 같은 문자로 이루어진 영역의 넓이를 구한다.
  • bfs 함수는 너비 우선 탐색을 이용하여 특정 좌표에서 상하좌우로 같은 문자로 이루어진 영역의 넓이를 구한다.
  • main 함수에서는 입력을 받고, 모든 좌표를 탐색하면서 방문하지 않은 좌표에 대해 dfs 또는 bfs 함수를 호출하여 ‘W’와 ‘B’로 구분된 영역의 넓이를 계산하고, 각각의 넓이를 누적하여 출력한다.