본문 바로가기

USACO/Bronze

백준 5958 Space Exploration (USACO January 2011 Bronze 3번)

문제 링크: 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

component의 갯수를 세면 됨.

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
#include <bits/stdc++.h>
using namespace std;
 
int n, v[1001][1001], dy[4= {-1100}, dx[4= {00-11};
char a[1001][1001];
 
void dfs(int y, int x) {
    v[y][x] = 1;
    for(int d = 0; d < 4; d++) {
        int yy = y + dy[d], xx = x + dx[d];
        if(yy >= 0 && xx >= 0 && yy < n && xx < n) {
            if(!v[yy][xx] && a[yy][xx] == '*')
                dfs(yy, xx);
        }
    }
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    cin >> n;
    for(int i = 0; i < n; i++for(int j = 0; j < n; j++)
        cin >> a[i][j];
 
    int ans = 0;
    for(int i = 0; i < n; i++for(int j = 0; j < n; j++) {
        if(!v[i][j] && a[i][j] == '*') {
            dfs(i, j);
            ans++;
        }
    }
 
    cout << ans << '\n';
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter