※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 5958번 문제인 Space Exploration이다.
문제는 아래 링크를 확인하자.

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

 

5958번: Space Exploration

Farmer John's cows have finally blasted off from earth and are now floating around space in their Moocraft. The cows want to reach their fiery kin on Jupiter's moon of Io, but to do this they must first navigate through the dangerous asteroid belt. Bessie

www.acmicpc.net

상하좌우로 연결된 * 덩어리의 개수를 세는 문제이다.

 

dfs 또는 bfs 등의 그래프 탐색 알고리즘을 이용해 connected component의 개수를 세어 문제를 해결하자.

 

아래 코드와 같이 dr과 dc배열과 같은 배열을 이용하면 탐색을 편하게 구현할 수 있다.

 

아래는 제출한 소스코드이다.

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

int N;
int dr[4] = { 1,-1,0,0 };
int dc[4] = { 0,0,1,-1 };
string board[1000];
void dfs(int r, int c) {
	for (int i = 0; i < 4; i++) {
		int rr = r + dr[i], cc = c + dc[i];
		if (rr < 0 || rr >= N || cc < 0 || cc >= N) continue;
		if (board[rr][cc] == '*') {
			board[rr][cc] = '.';
			dfs(rr, cc);
		}
	}
}

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);

	int cnt = 0;
	cin >> N;
	for (int r = 0; r < N; r++) cin >> board[r];

	for (int r = 0; r < N; r++) {
		for (int c = 0; c < N; c++) {
			if (board[r][c] == '*') {
				board[r][c] = '.';
				cnt++;
				dfs(r, c);
			}
		}
	}

	cout << cnt;
}
728x90

+ Recent posts