알고리즘/Backjoon
[C++] 1987 - 알파벳
ShinDongJun
2020. 1. 7. 14:06
문제 링크 : https://www.acmicpc.net/problem/1987
1987번: 알파벳
문제 세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으로 이동할 수 있는데, 새로 이동한 칸에 적혀 있는 알파벳은 지금까지 지나온 모든 칸에 적혀 있는 알파벳과는 달라야 한다. 즉, 같은 알파벳이 적힌 칸을 두 번 지날 수 없다. 좌측 상단에서 시작해서, 말이 최대한 몇 칸을 지날 수 있는지를 구하는
www.acmicpc.net
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
|
#include<iostream>
#include<algorithm>
#define endl '\n'
using namespace std;
char O['z'-'a'+1];
char board[21][21];
int X[4] = {0, 0, 1, -1};
int Y[4] = {1, -1, 0, 0};
int cnt;
int R,C;
void dfs(int y, int x, int c);
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> R >> C;
for(int i = 0; i < R; ++i)
cin >> board[i];
dfs(0, 0, 1);
cout << cnt << endl;
return 0;
}
void dfs(int y, int x, int c)
{
char tmp = board[y][x];
O[tmp-'A'] = 1;
board[y][x] = '\0';
if(cnt < c)
cnt = c;
for(int i = 0; i < 4; ++i)
{
if(0 <= y+Y[i] && y+Y[i] < R && 0 <= x+X[i] && x+X[i] < C)
{
if(!O[board[y+Y[i]][x+X[i]]-'A'] && board[y+Y[i]][x+X[i]])
dfs(y+Y[i], x+X[i], c+1);
}
}
board[y][x] = tmp;
O[tmp-'A'] = 0;
}
|