728x90
[Gold IV] 알파벳 - 1987
성능 요약
메모리: 15128 KB, 시간: 948 ms
분류
백트래킹, 깊이 우선 탐색, 그래프 이론, 그래프 탐색
문제 설명
세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다.
말은 상하좌우로 인접한 네 칸 중의 한 칸으로 이동할 수 있는데, 새로 이동한 칸에 적혀 있는 알파벳은 지금까지 지나온 모든 칸에 적혀 있는 알파벳과는 달라야 한다. 즉, 같은 알파벳이 적힌 칸을 두 번 지날 수 없다.
좌측 상단에서 시작해서, 말이 최대한 몇 칸을 지날 수 있는지를 구하는 프로그램을 작성하시오. 말이 지나는 칸은 좌측 상단의 칸도 포함된다.
입력
첫째 줄에 R과 C가 빈칸을 사이에 두고 주어진다. (1 ≤ R,C ≤ 20) 둘째 줄부터 R개의 줄에 걸쳐서 보드에 적혀 있는 C개의 대문자 알파벳들이 빈칸 없이 주어진다.
출력
첫째 줄에 말이 지날 수 있는 최대의 칸 수를 출력한다.
문제 풀이
DFS와 백트래킹을 사용해 미로에서 가능한 모든 경로를 탐색하고 가장 긴 경로를 찾으면 된다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int R;
static int C;
static int map[][] = new int[20][20];
static int cnt = 1;
static int ans = 1;
static int dx[] = {-1, 0, 1, 0};
static int dy[] = {0, -1, 0, 1};
static boolean[] visited = new boolean[26];
public static void dfs(int y, int x) {
int idx = map[y][x];
visited[idx] = true;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (-1 < nx && nx < C && -1 < ny && ny < R) {
int next = map[ny][nx];
if (!visited[next]) {
ans = Math.max(++cnt, ans);
dfs(ny, nx);
}
}
}
--cnt;
visited[idx] = false;
}
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
String line;
for (int i = 0; i < R; i++) {
line = br.readLine();
for (int j = 0; j < C; j++)
map[i][j] = (int) line.charAt(j);
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
map[i][j] = (char) (map[i][j] - 'A');
}
}
dfs(0, 0);
System.out.print(ans);
}
}
코드 풀이
static int R;
static int C;
static int map[][] = new int[20][20];
static int cnt = 1;
static int ans = 1;
static int dx[] = {-1, 0, 1, 0};
static int dy[] = {0, -1, 0, 1};
static boolean[] visited = new boolean[26];
R
,C
: 미로의 행과, 열을 입력받을 변수map
: 미로의 각 칸에 정보를 저장할 2차원 배열cnt
: 현재 경로의 길이를 나타낼 변수ans
: 탐색한 경로 중 가장 긴 경로의 길이를 저장할 변수dx
,dy
: 이동 방향으로 사용할 변수visited
: 알파벳이 방문했는지 확인할 변수
public static void dfs(int y, int x) {
int idx = map[y][x];
visited[idx] = true;
for (int i = 0; i < 4; i++) {
int ny = y + dy[i];
int nx = x + dx[i];
if (-1 < nx && nx < C && -1 < ny && ny < R) {
int next = map[ny][nx];
if (!visited[next]) {
ans = Math.max(++cnt, ans);
dfs(ny, nx);
}
}
}
--cnt;
visited[idx] = false;
}
- 현재 위치의 알파벳을 가져와서 해당 알파벳의
visited
를 true로 바꿔줌 dx
와dy
를 사용해서 다음 위치로 이동- 미로 범위 내에 있다면 다음 위치의 알파벳을 가져옴
- 다음 위치를 방문하지 않았다면 현재 경로 길이를 증가하고
ans
에 해당값을 저장후 다음 위치로 이동 - 현재 위치에서 더 이상 다음 위치가 없을 때 경로 길이를 감소
- 현재 위치를 다른 경로에서 방문할 수 있도록
visited
를 false로 저장
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
String line;
for (int i = 0; i < R; i++) {
line = br.readLine();
for (int j = 0; j < C; j++)
map[i][j] = (int) line.charAt(j);
}
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
map[i][j] = (char) (map[i][j] - 'A');
}
}
dfs(0, 0);
System.out.print(ans);
}
- 행과 열을 입력받음
map
의 각 칸에 알파벳 입력map
의 각 칸에 들어있는 알파벳을 정수로 변환- dfs를 호출해서 정답을 구함
728x90
'백준 문제풀이' 카테고리의 다른 글
[Baekjoon 14400] 편의점 2 - JAVA (0) | 2023.09.24 |
---|---|
[Baekjoon 1197] 최소 스패닝 트리 - JAA (0) | 2023.09.10 |
[Baekjoon 9527] 1의 개수 세기 - JAVA (0) | 2023.09.05 |
[Baekjoon 23291] 어항 정리 - JAVA (0) | 2023.09.03 |
[Baekjoon 8120] Coding of Permutations - JAVA (0) | 2023.09.01 |