[BOJ] 1987๋ฒ ์ํ๋ฒณ
https://www.acmicpc.net/problem/1987
๋ฌธ์ ์ ๊ทผ
๊ฐ๋ก R, ์ธ๋ก C๋ก ๋ ๋ณด๋์ ๋๋ฌธ์ ์ํ๋ฒณ์ด ์ ํ์๊ณ , ๊ฐ์ฅ ์ผ์ชฝ ์๋ถํฐ ์ํ๋ฒณ ๋น ํ๋ฒ์ฉ๋ง ๋ฐฉ๋ฌธํด์ ๊ฐ์ฅ ๋ฉ๋ฆฌ ๊ฐ ์ ์๋ ๊ธธ์ด๋ฅผ ๊ตฌํ๋ ๋ฌธ์ ์ด๋ค.
์ฒ์์๋ ์๋ฌด์๊ฐ ์์ด bfs๋ก ํ๋ค๊ฐ ์๊ฐํด๋ณด๋๊น dfs๊ฐ ๋ ๋ง๋ ๊ฒ ๊ฐ์์ ๋ฐฉํฅ์ ํ์๋ค.
์ฒ์์๋ ๋ณด๋์ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ์ ์ฅํ๋ isVisited์ ์ํ๋ฒณ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ์ ์ฅํ๋ alphabetVisited๋ฅผ ์ฌ์ฉํ๋ ค ํ๋๋ฐ, ์๊ฐํด๋ณด๋๊น ํ๋ฒ ๋ฐฉ๋ฌธํ ์ํ๋ฒณ์ ๋ฐฉ๋ฌธํ์ง ๋ชปํ๋๊น ๋ณด๋์ ๋ฐฉ๋ฌธ์ฌ๋ถ๋ฅผ ์ ์ฅํ ํ์๊ฐ ์๊ณ , ๊ฒฝ๋ก๋ฅผ String์ผ๋ก ๊ณ์ ์ถ๊ฐํด๊ฐ๋ฉด์ ํ๋ฉด ์ํ๋ฒณ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ ๋ฐ๋ก ์ ์ฅํ์ง ์์๋ ๋ ๊ฒ ๊ฐ์์ dfs์ ๊ฐ๋ ค๋ x,y์ ์ง๊ธ๊น์ง์ ๊ฒฝ๋ก๋ฅผ ๋ด์ path๋ฅผ ๋งค๊ฐ๋ณ์๋กํด์ ์ฝ๋๋ฅผ ์์ฑํ์๋ค.
Code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ1987 {
static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, -1, 1};
static char[][] alphabet;
static int R,C;
static int answer = 0;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] s = br.readLine().split(" ");
R = Integer.parseInt(s[0]);
C = Integer.parseInt(s[1]);
alphabet = new char[R][C];
for(int i = 0; i<R; i++){
alphabet[i] = br.readLine().toCharArray();
}
dfs(0, 0, String.valueOf(alphabet[0][0]));
System.out.println(answer);
}
public static void dfs(int x, int y, String path) {
answer = Math.max(answer,path.length());
for(int i = 0; i<4; i++){
int next_x = x + dx[i];
int next_y = y + dy[i];
if(isIn(next_x,next_y)) continue;
if(path.indexOf(alphabet[next_x][next_y]) != -1) continue;
dfs(next_x, next_y, path+alphabet[next_x][next_y]);
}
}
public static boolean isIn(int x, int y){
return x<0 || x >= R || y<0 || y>=C;
}
}
'Algorithm' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Algorithm/Java][๋ฐฑ์ค] 1062๋ฒ ๊ฐ๋ฅด์นจ (0) | 2022.05.16 |
---|---|
[Algorithm/Java][๋ฐฑ์ค] 2504๋ฒ ๊ดํธ์ ๊ฐ (0) | 2022.05.11 |
[Algorithm/Java][๋ฐฑ์ค] 2467๋ฒ ์ฉ์ก (0) | 2022.05.03 |
[Algorithm/Java][๋ฐฑ์ค] 12852๋ฒ 1๋ก ๋ง๋ค๊ธฐ 2 (0) | 2022.05.01 |
[Algorithm/Java][ํ๋ก๊ทธ๋๋จธ์ค] ๋จ์ฒด์ฌ์ง ์ฐ๊ธฐ (0) | 2022.05.01 |