[伯俊]P 1987
import java.util.LinkedHashSet;
import java.util.Scanner;
/*
* TC2)
* CAAB
* ADCB
* EDFC
* SFSC -> 3x 6o
*/
public class P1987 { // Flood-Fill
private static LinkedHashSet<Character> set;
private static char[][] matrix;
private static boolean[][] visit;
private static int[] dx = { 0, 0, -1, 1 };
private static int[] dy = { 1, -1, 0, 0 };
private static int r, c;
private static int answer;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
set = new LinkedHashSet<>();
r = sc.nextInt();
c = sc.nextInt();
matrix = new char[r][c];
visit = new boolean[r][c];
for (int i = 0; i < r; i++) {
char[] input = sc.next().toCharArray();
for (int j = 0; j < c; j++) {
matrix[i][j] = input[j];
}
}
set.add(matrix[0][0]);
dfs(0, 0, 1);
System.out.println(answer);
sc.close();
}
private static void dfs(int x, int y, int max) {
answer = answer < max ? max : answer; // 최대값 저장
if (visit[x][y]) return ;
for (int i = 0; i < 4; i++) {
int newX = x + dx[i];
int newY = y + dy[i];
if (isValid(newX, newY) && !set.contains(matrix[newX][newY])) { // 새로운 알파벳이 set에 없을 때 이동
visit[x][y] = true;
set.add(matrix[newX][newY]);
dfs(newX, newY, max + 1); // max + 1 로 dfs 함으로써 최대값을 구함
visit[x][y] = false; // 모든 경우를 봐야하므로 다시 false
set.remove(matrix[newX][newY]); // 모든 경우를 봐야하므로 다시 set.remove()
}
}
}
private static boolean isValid(int x, int y) {
return x < 0 || x >= r || y < 0 || y >= c ? false : true;
}
}
Reference
この問題について([伯俊]P 1987), 我々は、より多くの情報をここで見つけました https://velog.io/@kmdngmn/백준-P1987テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol