알고리즘/문제풀이
[백준] 1987. 알파벳
BSHwan
2020. 7. 10. 23:10
반응형
https://www.acmicpc.net/problem/1987
1987번: 알파벳
문제 세로 R칸, 가로 C칸으로 된 표 모양의 보드가 있다. 보드의 각 칸에는 대문자 알파벳이 하나씩 적혀 있고, 좌측 상단 칸 (1행 1열) 에는 말이 놓여 있다. 말은 상하좌우로 인접한 네 칸 중의 한
www.acmicpc.net
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int R, C, answer, cnt;
static char[][] map;
static boolean[][] visited;
static int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
static boolean[] check;
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());
map = new char[R][C];
for(int i=0; i<R; i++) {
String s = br.readLine();
for(int j=0; j<C; j++) {
map[i][j] = s.charAt(j);
}
}
visited = new boolean[R][C];
check = new boolean[91];
DFS(0, 0);
System.out.println(answer+1);
}
public static void DFS(int x, int y) {
answer = Math.max(cnt, answer);
visited[x][y] = true;
check[map[x][y]] = true;
for(int i=0; i<4; i++) {
int nx = x + dir[i][0];
int ny = y + dir[i][1];
if(isInside(nx, ny) && !visited[nx][ny] && !check[map[nx][ny]]) {
cnt++;
visited[nx][ny] = true;
check[map[nx][ny]] = true;
DFS(nx, ny);
visited[nx][ny] = false;
check[map[nx][ny]] = false;
cnt--;
}
}
}
public static boolean isInside(int x, int y) {
return x>=0 && x<R && y>=0 && y<C;
}
}
반응형