문제 >> [SWEA] 1949. 등산로 조성
![](http://cdn.tour-ntpc.com/site/a3be84a9-7283-40a3-b4c7-758bf39c7828/Content/Upload/Place/fac2f59a-4e13-42bc-8107-bd1be3917783.jpg)
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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | mport java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.StringTokenizer; //SWEA :: 1949 등산로조성 //2019-04-01 public class Solution1949_등산로조성 { private static int[][] map; private static boolean[][] visit; private static int N; private static int K; private static ArrayList<pair> top; private static int bottom; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int T = Integer.parseInt(br.readLine()); for (int tc = 1; tc <= T; tc++) { StringTokenizer st = new StringTokenizer(br.readLine(), " "); N = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); // 최대 K만큼 한 번 지형을 깎는다 map = new int[N][N]; top = new ArrayList<>(); int max = -1; bottom = 21; for (int i = 0; i < N; i++) { st = new StringTokenizer(br.readLine(), " "); for (int j = 0; j < N; j++) { map[i][j] = Integer.parseInt(st.nextToken()); if (max < map[i][j]) { max = map[i][j]; top.clear(); top.add(new pair(i, j)); } else if (max == map[i][j]) { top.add(new pair(i, j)); } bottom = bottom > map[i][j] ? map[i][j] : bottom; } } ////// input ans = -1; for (pair p : top) { visit = new boolean[N][N]; dfs(p.y, p.x, 1, false); } System.out.println("#" + tc + " " + ans); } // end of tc }// end of main static int[] dy = { -1, 1, 0, 0 }; static int[] dx = { 0, 0, -1, 1 }; static int ans; private static void dfs(int y, int x, int len, boolean cut) { // cut이 true 면 공사를 했다. visit[y][x] = true; ans = ans < len ? len : ans; for (int i = 0; i < 4; i++) { int ny = y + dy[i]; int nx = x + dx[i]; if (ny < 0 || ny > N - 1 || nx < 0 || nx > N - 1 || visit[ny][nx]) continue; if (map[ny][nx] < map[y][x]) { dfs(ny, nx, len + 1, cut); } else { // 같거나 높으면 if (!cut) { // cut이 false면 아직 공사를 안한 상태 for (int k = 1; k <= K; k++) { int tmp = map[ny][nx]; map[ny][nx] -= k; if (map[ny][nx] < map[y][x]) dfs(ny, nx, len + 1, true); map[ny][nx] = tmp; } } } visit[ny][nx] = false; } } static class pair { int y; int x; public pair(int y, int x) { super(); this.y = y; this.x = x; } } } | cs |
dfs와 약간의 백트래킹을 이용해 풀었습니다 ~~~~~
'Algorithm Problem Solving' 카테고리의 다른 글
[BOJ] 1938 통나무 옮기기 (0) | 2019.04.05 |
---|---|
[SWEA] 2383. 점심식사 시간 (5) | 2019.04.04 |
[BOJ] 1805. 나무자르기 (4) | 2019.03.22 |
[BOJ] 14502 : 연구소 (2) | 2019.03.12 |
[BOJ] 17070 : 파이프 옮기기 1 (0) | 2019.03.12 |