-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1987.cpp
63 lines (56 loc) · 1 KB
/
1987.cpp
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
// 1987. 알파벳
// 2019.05.19
// DFS, 백트래킹
#include<iostream>
using namespace std;
int r, c;
char map[21][21];
bool visit[26]; // A~Z까지의 방문 여부
int dx[4] = { 0,0,1,-1 };
int dy[4] = { 1,-1,0,0 };
int ans;
void DFS(int x, int y, int cnt)
{
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (xx < 0 || yy < 0 || xx >= r || yy >= c)
{
continue;
}
// 다음 위치의 알파벳이 아직 지나온 알파벳이 아닐 경우
if (!visit[map[xx][yy] - 'A'])
{
visit[map[xx][yy] - 'A'] = true;
DFS(xx, yy, cnt + 1);
// 찾는게 끝나면 원래대로 돌림
visit[map[xx][yy] - 'A'] = false;
}
else
{
if (ans < cnt)
{
ans = cnt;
}
}
}
}
int main()
{
cin >> r >> c;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
cin >> map[i][j];
}
}
// 시작점과 시작점의 방문을 true로 만듦
int x = 0;
int y = 0;
visit[map[x][y] - 'A'] = true;
DFS(x, y, 1);
cout << ans << endl;
return 0;
}