📖 문제 링크
https://www.acmicpc.net/problem/1987
1987번: 알파벳
세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한 칸으
www.acmicpc.net
✅ 최종 코드
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main_BJ_1987_알파벳3 {
static int R, C, cnt;
static int[][] board;
static boolean[] alphabet = new boolean[26];
static int[] dx = { -1, 0, 1, 0}; //상 우 하 좌
static int[] dy = { 0, 1, 0, -1};
static int max = Integer.MIN_VALUE;
public static void main(String[] args) throws Exception {
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 int[R][C];
for (int i = 0; i < R; i++) {
String str = br.readLine();
for (int j = 0; j < C; j++) {
board[i][j] = str.charAt(j) - 'A';
}
}
dfs(0, 0, 1);
System.out.println(max);
}//main
private static void dfs(int x, int y, int cnt) {
if(max == 26) return;
alphabet[board[x][y]] = true;
int nx, ny;
for(int i=0;i<4;i++) {
nx = x + dx[i];
ny = y + dy[i];
if(nx >= 0 && nx < R && ny >= 0 && ny < C && !alphabet[board[nx][ny]]) {
alphabet[board[nx][ny]] = true;
dfs(nx, ny, cnt+1);
alphabet[board[nx][ny]] = false;
}
}
max = Math.max(max, cnt);
return;
}//end dfs
}//end class
'알고리즘 > Java' 카테고리의 다른 글
[백준/JAVA] 16935번 : 배열돌리기3 (0) | 2022.08.14 |
---|---|
[백준/JAVA] 16926번 : 배열 돌리기1 (0) | 2022.08.14 |
[백준/JAVA] 2751번 : 수정렬하기2 (0) | 2022.08.12 |
[백준/JAVA] 10815번 : 숫자카드 (0) | 2022.08.12 |
[SWEA/JAVA] 1861번 : 정사각형방 (0) | 2022.08.09 |