[ 문제 ]
세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다.
보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다.
말은 상하좌우로 인접한 네 칸 중의 한 칸으로 이동할 수 있는데,
새로 이동한 칸에 적혀 있는 알파벳은 지금까지 지나온 모든 칸에 적혀 있는 알파벳과는 달라야 한다.
즉, 같은 알파벳이 적힌 칸을 두 번 지날 수 없다.
좌측 상단에서 시작해서, 말이 최대한 몇 칸을 지날 수 있는지를 구하는 프로그램을 작성하시오.
말이 지나는 칸은 좌측 상단의 칸도 포함된다.
[ 입력 ]
- 첫째 줄에 R과 C가 빈칸을 사이에 두고 주어진다. (1 ≤ R,C ≤ 20)
- 둘째 줄부터 R개의 줄에 걸쳐서 보드에 적혀 있는 C개의 대문자 알파벳들이 빈칸 없이 주어진다.
[ 출력 ]
- 첫째 줄에 말이 지날 수 있는 최대의 칸 수를 출력한다.
[ 입력 예제 ]
2 4
CAAB
ADCB
[ 출력 예제 ]
3
import java.io.*;
import java.util.*;
public class Main {
static int R, C;
static char[][] board;
static int[] dr = {0, -1, 0, 1};
static int[] dc = {1, 0, -1, 0};
static ArrayList<Character> list; // 알파벳을 담을 리스트
static int max;
private static boolean isAvailable (int row, int column) { // 유망 여부 체크
if (row >= 0 && row < R && column >= 0 && column < C && !list.contains(board[row][column]))
return true;
return false;
}
private static void alphabet (int row, int column) {
list.add(board[row][column]);
for (int d = 0; d < 4; d++) {
if(isAvailable(row+dr[d], column+dc[d]))
alphabet(row+dr[d], column+dc[d]);
}
// 4방향 모두 불가할 경우
max = Math.max(list.size(), max); // 최대값 갱신
list.remove(list.size() - 1); // 추가한 알파벳 삭제
return;
}
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()); // 보드의 열
board = new char[R][C];
for(int r = 0; r < R; r++)
board[r] = br.readLine().toCharArray();
list = new ArrayList<>();
max = Integer.MIN_VALUE;
alphabet(0, 0);
System.out.println(max);
}
}
'Algorithm > 백준+프로그래머스+SWEA+정올+구름' 카테고리의 다른 글
[Algorithm] 백준 2839 설탕 배달 (0) | 2021.08.20 |
---|---|
[Algorithm] SWEA 1247 최적경로 (0) | 2021.08.20 |
[Algorithm] 백준 3109 빵집 (0) | 2021.08.20 |
[Algorithm] 백준 1074 Z (0) | 2021.08.19 |
[Algorithm] 백준 1992 쿼드트리 (0) | 2021.08.19 |