๋ฌธ์
https://www.acmicpc.net/problem/1987
๋ด ๋ฌธ์ ํ์ด
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int r, c;
static char[][] board;
static int max = 0;
public static void dfs(int x, int y, boolean[] alphabet, int cnt) {
if(x < 0 || y < 0 || x >= r || y >= c) return;
if(alphabet[(int)board[x][y]-65]) { // ์ด๋ฏธ ์ฐ์ฌ์ง ์ํ๋ฒณ ๋ง๋ ์ ๋ฆฌํด
max = Math.max(max, cnt);
return;
}
alphabet[(int)board[x][y]-65] = true; // ํ์ฌ ์ํ๋ฒณ์ด ์ฐ์์์ ํ์
dfs(x-1, y, alphabet, cnt+1);
dfs(x, y-1, alphabet, cnt+1);
dfs(x+1, y, alphabet, cnt+1);
dfs(x, y+1, alphabet, cnt+1);
alphabet[(int)board[x][y]-65] = false;
}
public static void main(String[] args) throws Exception {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
st = new StringTokenizer(in.readLine());
r = Integer.parseInt(st.nextToken());
c = Integer.parseInt(st.nextToken());
board = new char[r][c];
for(int i = 0; i < r; i++) {
String now = in.readLine();
for(int j = 0; j < c; j++) {
board[i][j] = now.charAt(j);
}
}
dfs(0, 0, new boolean[26], 0);
System.out.println(max);
}
}
๐ DFS ๋ฌธ์
- ํ์๋ง๋ค ์ด๋ค ์ํ๋ฒณ์ด ์ฐ์๋์ง ์ฒดํฌํด์ค alphabet ๋ฐฐ์ด์ ๋ง๋ค์ด์ฃผ์๋ค.
์ฒซ ๋ฒ์งธ ์ธ๋ฑ์ค๋ถํฐ ์ํ๋ฒณ ์์๋๋ก ์ฒดํฌํ ์ ์๋๋ก ํ๋๋ฐ,
์ฒดํฌํ ๋๋ ํด๋นํ๋ ์ํ๋ฒณ์ intํ์ผ๋ก ๋ณํํ ํ, 65๋ฅผ ๋นผ์ฃผ์ด ์ธ๋ฑ์ค๋ก ์ฌ์ฉํ๋ค. - dfs ํ์๋ง๋ค ์ฐ์ธ ์ํ๋ฒณ์ ์ฒดํฌํ๊ณ , ๋ช ๋ฒ์งธ ์ํ๋ฒณ์ธ์ง ์นด์ดํ
ํด์ฃผ์๋๋ฐ,
์ด๋ฏธ ์ฐ์ฌ์ง ์ํ๋ฒณ์ ๋๋ค์ ๋ง๋๋ฉด ๊ทธ ๋๋ max ๊ฐ์ ๊ฐฑ์ ํ๊ณ ๋ฆฌํดํ๋ค.
๐ก ํผ๋๋ฐฑ
- ์ฝ๊ฒ ํ ์ ์๋ ๋ฌธ์ ์๋ค. ํ์ง๋ง! ์๊ฐ ๋ณต์ก๋๊ฐ ๋ ์์ข์์ ๋ค์ ํ ๋ฒ ๋ด์ผ ํ ๋ฏ ์ถ๋ค.
'2๏ธโฃ Java > Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java Algorithm] Z BOJ #1074 (0) | 2022.08.16 |
---|---|
[Java Algorithm] ๋์ฅ๊ณ JUNGOL #1828 (0) | 2022.08.16 |
[Java Algorithm] ๋ ๋์ BOJ #16197 (0) | 2022.08.16 |
[Java Algorithm] ์จ๋ฐ๊ผญ์ง 2 BOJ #12851 (0) | 2022.08.16 |
[Java Algorithm] ์ฌ์น์ฐ์ฐ ์ ํจ์ฑ ๊ฒ์ฌ SWEA #1233 (0) | 2022.08.11 |
๋๊ธ