문제 👉🏻 https://www.acmicpc.net/problem/1987
인접한 알파벳 칸을 이동할 때, 말의 최대 이동 칸 수 구하기
백트래킹을 활용하여 최대로 이동할 수 있는 거리를 얻을 수 있다.
지나온 알파벳과 중복되면 안 되기 때문에 이미 지나온 알파벳은 Set에 넣어 이동할 수 있는 칸인지 확인해야 한다.
칸 이동
이동 가능한 좌표이고, 해당 칸의 알파벳이 중복되지 않으면 이동
최대 이동 거리 구하기
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;
public class Main {
static final int[] moveX = {1, -1, 0, 0};
static final int[] moveY = {0, 0, 1, -1};
static int max;
public static void dfs(int r, int c, char[][] map, int count, int x, int y, Set<Character> visited) {
if(max < count) max = count;
for(int i = 0; i < 4; i++) {
int nextX = x + moveX[i];
int nextY = y + moveY[i];
if(nextX < 0 || nextY < 0 || nextX >= r || nextY >= c) continue;
if(visited.contains(map[nextX][nextY])) continue;
visited.add(map[nextX][nextY]);
dfs(r, c, map, count + 1, nextX, nextY, visited);
visited.remove(map[nextX][nextY]);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int r = Integer.parseInt(input[0]);
int c = Integer.parseInt(input[1]);
char[][] map = new char[r][c];
for (int i = 0; i < r; i++) {
String mapInput = br.readLine();
for (int j = 0; j < c; j++) {
map[i][j] = mapInput.charAt(j);
}
}
Set<Character> visited = new HashSet<>();
visited.add(map[0][0]);
dfs(r, c, map,1, 0, 0, visited);
System.out.println(max);
}
}
이동한 칸의 알파벳이 중복되지 않도록 구현할 방법을 찾아내면 쉽게 풀 수 있는 문제였다.
그 방법도 Set으로 풀면될거라는 생각을 금방 해낼 수 있었다.
백트래킹 문제를 처음 풀 때 쉬운 문제였음에도 동작 원리를 제대로 알지 못해서 해결하는데 오랜 시간이 걸렸다.
해당 문제를 풀면서 백트래킹 문제풀이에 자신감이 생겼고, 동작 원리에 대한 이해도도 이전보다 높아졌음을 체감할 수 있었다.