알고리즘/백준

[백준 1987] 알파벳 C++

겜도리도리 2021. 10. 8. 22:48
반응형

문제

백준 1987 C++

 

1987번: 알파벳

세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으

www.acmicpc.net

풀이

0, 0 지점부터 DFS를 실행하여 최대 깊이를 구해줍니다.

해당 지점을 방문했는지를 저장하는 mapvisited 배열과

해당 문자열을 방문했는지를 저장하는 charvisited 배열을 모두 사용하여 방문 체크를 합니다.

소스 코드

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
#include <iostream>
#include <algorithm>
using namespace std;
 
bool mapvisited[20][20];
bool charvisited[26];
char map[20][20];
 
int R, C;
int dx[] = { 00-11 };
int dy[] = { -1100 };
int maxdepth = 0;
 
void dfs(int x, int y, int depth) {
    // 방문 처리
    mapvisited[y][x] = true;
    // 알파벳 방문 처리
    charvisited[map[y][x] - 65= true;
    maxdepth = max(maxdepth, depth);
    for (int i = 0; i < 4; i++) {
        // DFS
        int nx = x + dx[i];
        int ny = y + dy[i];
        // 다음 문자열
        int nc = map[ny][nx] - 65;
        if (nx >= 0 && ny >= 0 && nx < C && ny < R) {
            if (!mapvisited[ny][nx] && !charvisited[nc]) {
                dfs(nx, ny, depth + 1);
                mapvisited[ny][nx] = false;
                charvisited[nc] = false;
            }
        }
    }
}
 
int main()
{
    cin >> R >> C;
    for (int i = 0; i < R; i++) {
        string s;
        cin >> s;
        for (int j = 0; j < s.length(); j++) {
            map[i][j] = s[j];
        }
    }
    dfs(001);
    cout << maxdepth;
    return 0;
}
cs
반응형

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

[백준 1717] 집합의 표현 C++  (0) 2021.10.11
[백준 2206] 벽 부수고 이동하기 C++  (0) 2021.10.09
[백준 14719] 빗물 C++  (0) 2021.10.07
[백준 13398] 연속합 2 C++  (0) 2021.10.07
[백준 2660] 회장뽑기 C++  (0) 2021.10.05