알고리즘 문제 풀이/sw아카데미
[swea] 수지의 수지 맞는 여행 - 7699
h982
2021. 4. 13. 22:55
문제설명
SW Expert Academy
SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!
swexpertacademy.com
기본아이디어
갈 수 있는 섬의 알파벳 명물이 겹치지 않기 때문에 구해야 하는 최대 거리는 알파벳 수 26을 넘지 않는다. 섬의 알파벳을 체크하므로 방문 체크는 생략해도 되고, 마지막에 알파벳 26개를 다 찾은 경우에는 최대의 경우가 이미 구해졌으므로 탈출 조건을 세팅해서 dfs 탐색을 종료하도록 만들었다.
구현코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
public static void main(String[] args) throws IOException {
int T = Integer.parseInt(input.readLine());
for(int test_case = 1; test_case <= T; test_case++){
StringTokenizer st = new StringTokenizer(input.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
map = new char[R][];
for(int i = 0; i < R; i++)
map[i] = input.readLine().toCharArray();
alpha = new boolean['Z'-'A' + 1];
max_dist = 0;
flag = false;
alpha[map[0][0] - 'A'] = true;
dfs(0,0, 1);
output.append("#" + test_case + " " + max_dist + "\n");
}
System.out.println(output);
}
static int R, C;
static char[][] map;
static boolean[] alpha;
static int max_dist;
static int[] dr = {0, 0, 1, -1};
static int[] dc = {1, -1, 0, 0};
static boolean flag;
static void dfs(int r, int c, int sum){
for(int d = 0; d < 4; d++){
int nr = r + dr[d];
int nc = c + dc[d];
if(isIn(nr,nc) && !alpha[map[nr][nc]-'A']){
alpha[map[nr][nc]-'A'] = true;
dfs(nr, nc, sum+1);
alpha[map[nr][nc]-'A'] = false;
}
if(flag)
return;
}
if(sum > max_dist) {
if(sum == 26)
flag = true;
max_dist = sum;
}
}
static boolean isIn(int r, int c){
return r >= 0 && r < R && c >= 0 && c < C;
}
|
cs |
정리, 기억할 내용
1. flag 탈출 조건이 없으면 시간차이 많이남 -> dfs 탈출 조건 생각하기