Creative Code

[1987번]알파벳 본문

백준 문제풀이

[1987번]알파벳

빛하루 2023. 9. 25. 12:24

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

 

1987번: 알파벳

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

www.acmicpc.net

#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <string>
#include <cmath>
#include <stack>

using namespace std;

int result = 0;  // 최종 결과를 저장할 변수

// 게임 보드와 그 크기를 저장할 변수들
char board[21][21];
bool visit[26] = { false };
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
int R, C;

// 깊이 우선 탐색 함수 (DFS)
void dfs(int a, int b, int cnt) {
    for (int i = 0; i < 4; i++) {
        int nx = a + dx[i];
        int ny = b + dy[i];
        if (nx < 0 || ny < 0 || nx == R || ny == C || visit[board[nx][ny] - 'A'] == true) {
            result = max(result, cnt);
            continue;
        }
        else {
            visit[board[nx][ny] - 'A'] = true;
            dfs(nx, ny, cnt+1);
            visit[board[nx][ny] - 'A'] = false;
        }
    }

}

int main() {
    cout.tie(0);
    cin.tie(0);
    ios_base::sync_with_stdio(false);

    cin >> R >> C;  // 보드 크기 입력

    // 보드의 문자열 입력
    for (int i = 0; i < R; i++) {
        for (int j = 0; j < C; j++) {
            cin >> board[i][j];
        }
    }
    visit[board[0][0]-'A'] = true;
    dfs(0, 0, 1);  // DFS 함수 호출
    cout << result;
}

'백준 문제풀이' 카테고리의 다른 글

[2312번]수 복원하기  (0) 2024.01.27
[2638번]치즈  (0) 2023.09.25
[9251번]LCS  (0) 2023.09.25
[17144번]미세먼지 안녕!  (0) 2023.09.24
[14502번]연구소  (0) 2023.09.24