[๋ฐฑ์ค] ๐ฅ 1987 ์ํ๋ฒณ
๐ ๋์ด๋
๐ฅ Gold 4
๐ ๋ฌธ์
https://www.acmicpc.net/problem/1987
๐ ํ์ด
๋ชจ๋ ๋ฌธ์ ๋ฅผ BFS๋ก ํ ์ ์๋ค๊ณ ์์ ๋ง๋งํ๋ ๋์ ์ ์ ์ ์ธ ์ถฉ๊ฒฉ์ ์ค ๋ฌธ์ ์๋ค.
BFS๋ก ์ด ๋ฌธ์ ๋ฅผ ๊ตฌํํ๋ ค๋ฉด ์ค๋ณต์ด ๋๋ฌด๋๋ ๋ง์ด ๋ฐ์ํ์ฌ, ๋ฉ๋ชจ๋ฆฌ์ด๊ณผ๊ฐ ๋ฐ ์ ๋ฐ์ ์๋ ๋ฌธ์ ์๋ค.
๋ฐ๋ผ์, ์ฒ์์ผ๋ก ์ฌ๊ทํจ์๋ฅผ ์ด์ฉํ์ฌ DFS๋ฅผ ๊ตฌํํด ๋ณด์๋ค.
๐ Code
package BOJ.DFS;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Stack;
import java.util.StringTokenizer;
public class N1987 {
static int R;
static int C;
static int[][] board;
static boolean[] visited;
static final int[] DR = {-1, 0, 1, 0};
static final int[] DC = {0, 1, 0, -1};
static int max;
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 int[R][C];
visited = new boolean[26];
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';
}
}
max = 0;
DFS(0, 0, 0);
System.out.println(max);
}
static void DFS(int r, int c, int count) {
if (visited[board[r][c]]) {
max = Math.max(max, count);
return;
} else {
visited[board[r][c]] = true;
for (int i = 0; i < DR.length; i++) {
int nextR = r + DR[i];
int nextC = c + DC[i];
if (nextR < 0 || nextR >= R || nextC < 0 || nextC >= C) {
continue;
}
DFS(nextR, nextC, count + 1);
}
visited[board[r][c]] = false;
}
}
}
package (์ด๋ฆ); ๋ฅผ ๋๊ณ , class ์ด๋ฆ์ Main
์ผ๋ก ๋ณ๊ฒฝํ๋ฉด ๋๋ค.
๊ฐ์ธ ๊ณต๋ถ ๊ธฐ๋ก์ฉ ๋ธ๋ก๊ทธ์
๋๋ค.
ํ๋ฆฌ๊ฑฐ๋ ์ค๋ฅ๊ฐ ์์ ๊ฒฝ์ฐ ์ ๋ณดํด์ฃผ์๋ฉด ๊ฐ์ฌํ๊ฒ ์ต๋๋ค.๐