출처: https://bumcrush.tistory.com/182 [맑음때때로 여름]
https://www.acmicpc.net/problem/1987
1987번: 알파벳
문제 세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한
www.acmicpc.net
#include <iostream>
using namespace std;
const int MAX = 20;
int R, C;
string graph[MAX];
bool alphaVisited[26] = {false};
typedef struct
{
int x, y;
} Dir;
Dir Dirmove[4] = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
int ans;
void dfs(int x, int y, int cnt)
{
ans = max(ans, cnt);
for (int i = 0; i < 4; i++)
{
int nextX = x + Dirmove[i].x;
int nextY = y + Dirmove[i].y;
if (0 <= nextX && nextX < R && 0 <= nextY && nextY < C && !alphaVisited[graph[nextX][nextY] - 'A'])
{
alphaVisited[graph[nextX][nextY] - 'A'] = true;
dfs(nextX, nextY, cnt + 1);
alphaVisited[graph[nextX][nextY] - 'A'] = false;
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cin >> R >> C;
for (int i = 0; i < R; i++)
cin >> graph[i];
int cnt = 1;
alphaVisited[graph[0][0] - 'A'] = true;
dfs(0, 0, cnt);
cout << ans;
}
굉장히 어려우면서도 재밌었다. 단순한 dfs 문제만 풀다가 백트래킹이 가미된 문제를 처음 풀다보니 너무 많이 헤매긴 했지만 얻어가는게 많았던 문제다.
입력이 대문자로만 이루어지기 때문에 -'A'를 하게 되면 A에서 부터 Z까지 0~26이 된다. 이를 이용하면 더 직관적인 코드를 짤 수 있다.
백준 1389 케빈 베이컨의 6단계 법칙(Floyd Warshall) (0) | 2020.07.26 |
---|---|
백준 10026 적록색약(dfs) (0) | 2020.07.26 |
백준 2583 영역 구하기(dfs) (0) | 2020.07.25 |
백준 2468 안전 영역(dfs) (0) | 2020.07.23 |
백준 14502 연구소(dfs) (0) | 2020.07.23 |
댓글 영역