본문 바로가기

알고리즘/BOJ

15559번

15559번 - 내 선물을 받아줘


처음에 단순히 연결요소의 갯수 문제라고 생각했는데, 한번 더 생각해야 했다.


내가 지금 있는 지점에서 움직일 수 있는 좌표와


내가 지금 있는 지점으로 올 수 있는 좌표를 모두 dfs를 통해서 체크하였다.


그래서 연결 요소가 총 몇개가 나올 수 있는지를 확인하면 되는 문제였다.


<정답 코드>


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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
#include<iostream>
#include<string>
using namespace std;
 
int n, m, ans;
char map[1001][1001];
bool chk[1001][1001];
int dx[4= { 0,0,1,-1 };
int dy[4= { 1,-1,0,0 };
void dfs(int x, int y)
{
    chk[x][y] = true;
 
 
    //현재 지점에서 움직일 수 있는 좌표
    int nx, ny;
    if (map[x][y] == 'S')
    {
        nx = x + 1;
        ny = y;
    }
    else if (map[x][y] == 'N')
    {
        nx = x - 1;
        ny = y;
    }
    else if (map[x][y] == 'E')
    {
        nx = x;
        ny = y + 1;
    }
    else if (map[x][y] == 'W')
    {
        nx = x;
        ny = y - 1;
    }
 
    if (nx >= 0 && ny >= 0 && nx < n && ny < m && !chk[nx][ny])
    {
        dfs(nx, ny);
    }
 
 
    //현재지점으로 올 수 있는 좌표
    for (int d = 0; d < 4; d++)
    {
        nx = x + dx[d];
        ny = y + dy[d];
        if (nx >= 0 && ny >= 0 && nx < n && ny < m && !chk[nx][ny])
        {
            if (map[nx][ny] == 'S' && d == 3)
            {
                dfs(nx, ny);
            }
            else if (map[nx][ny] == 'N' && d == 2)
            {
                dfs(nx, ny);
            }
            else if (map[nx][ny] == 'E' && d == 1)
            {
                dfs(nx, ny);
            }
            else if (map[nx][ny] == 'W' && d == 0)
            {
                dfs(nx, ny);
            }
        }
    }
 
}
int main()
{
    //freopen("input.txt", "r", stdin);
    ios::sync_with_stdio(false);
    cin.tie(NULL);
 
    cin >> n >> m;
 
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            cin >> map[i][j];
        }
    }
 
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < m; j++)
        {
            if (!chk[i][j])
            {
                ans++;
                dfs(i, j);
            }
        }
    }
 
    cout << ans;
    
    return 0;
}
cs


반응형

'알고리즘 > BOJ' 카테고리의 다른 글

11559  (0) 2018.04.11
1793번  (0) 2018.03.25
2484번  (0) 2018.03.25
3665번(다시풀기)  (0) 2018.03.25
10825번  (0) 2018.03.24