본문 바로가기

USACO/Silver

백준 11975 Build Gates (USACO January 2016 Silver 3번)

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

 

11975번: Build Gates

The first line of input contains \(N\) (\(1 \leq N \leq 1000\)). The next line contains a string of length \(N\) describing FJ's path. Each character is either N (north), E (east), S (south), or W (west).

www.acmicpc.net

BFS

방향 char를 하나 받을때마다 두칸씩 해당 방향으로 움직이면서 fence를 설치함. 다 설치하고 나서, fence가 없는곳에서 bfs를 실행시키고, 실행 횟수에서 1을 빼면 답임.

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
#include <bits/stdc++.h>
using namespace std;
 
int n, a[4001][4001], dy[4= {-1100}, dx[4= {00-11};
queue<pair<intint>> q;
 
void bfs(int y, int x) {
    a[y][x] = 1;
    q.push({y, x});
 
    while(!q.empty()) {
        int cy = q.front().first, cx = q.front().second;
        q.pop();
        for(int d = 0; d < 4; d++) {
            int ny = cy + dy[d], nx = cx + dx[d];
            if(ny >= 0 && nx >= 0 && ny <= 4000 && nx <= 4000 && a[ny][nx] == 0) {
                a[ny][nx] = 1;
                q.push({ny, nx});
            }
        }
    }
}
 
int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
 
    int y = 2000, x = 2000;
    a[y][x] = 1;
 
    cin >> n;
    while(n--) {
        char d;
        cin >> d;
 
        int yy, xx;
        for(int i = 0; i < 2; i++) {
            if(d == 'N')
                yy = y + dy[0], xx = x + dx[0];
            if(d == 'S')
                yy = y + dy[1], xx = x + dx[1];
            if(d == 'W')
                yy = y + dy[2], xx = x + dx[2];
            if(d == 'E')
                yy = y + dy[3], xx = x + dx[3];
 
            a[yy][xx] = 1;
            y = yy;
            x = xx;
        }
    }
 
    int ans = -1;
    for(int i = 0; i <= 4000; i++for(int j = 0; j <= 4000; j++) {
        if(a[i][j] == 0) {
            bfs(i, j);
            ans++;
        }
    }
 
    cout << ans << '\n';
    return 0;
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter