|
| 1 | +package DFS.P14500; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int N, M; |
| 9 | + static int[][] board; |
| 10 | + |
| 11 | + static boolean[][] visited; |
| 12 | + static int[] di = {-1, 0, 1, 0}; |
| 13 | + static int[] dj = {0, 1, 0, -1}; |
| 14 | + static int ans = 0; |
| 15 | + |
| 16 | + public static void main(String[] args) throws Exception { |
| 17 | + System.setIn(new FileInputStream("src/DFS/P14500/input.txt")); |
| 18 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 19 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 20 | + |
| 21 | + N = Integer.parseInt(st.nextToken()); |
| 22 | + M = Integer.parseInt(st.nextToken()); |
| 23 | + board = new int[N][M]; |
| 24 | + |
| 25 | + for (int i = 0; i < N; i++) { |
| 26 | + st = new StringTokenizer(br.readLine()); |
| 27 | + for (int j = 0; j < M; j++) { |
| 28 | + board[i][j] = Integer.parseInt(st.nextToken()); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + visited = new boolean[N][M]; |
| 33 | + for (int i = 0; i < N; i++) { |
| 34 | + for (int j = 0; j < M; j++) { |
| 35 | + makeFuck(i, j); |
| 36 | + dfs(i, j, 0, 0); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + System.out.println(ans); |
| 41 | + } |
| 42 | + |
| 43 | + static void makeFuck(int i, int j) { |
| 44 | + int min = Integer.MAX_VALUE; |
| 45 | + int sum = board[i][j]; |
| 46 | + int count = 0; |
| 47 | + |
| 48 | + for (int t = 0; t < 4; t++) { |
| 49 | + int to_i = i + di[t]; |
| 50 | + int to_j = j + dj[t]; |
| 51 | + |
| 52 | + if (isValidPath(to_i, to_j)) { |
| 53 | + min = Math.min(min, board[to_i][to_j]); |
| 54 | + sum += board[to_i][to_j]; |
| 55 | + count ++; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + if (count == 3) ans = Math.max(ans, sum); |
| 60 | + else if (count == 4) ans = Math.max(ans, sum - min); |
| 61 | + } |
| 62 | + |
| 63 | + static void dfs(int si, int sj, int count, int sum) { |
| 64 | + if (count == 4) { |
| 65 | + ans = Math.max(ans, sum); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + visited[si][sj] = true; |
| 70 | + for (int i = 0; i < 4; i++) { |
| 71 | + int to_i = si + di[i]; |
| 72 | + int to_j = sj + dj[i]; |
| 73 | + |
| 74 | + if (isValidPath(to_i, to_j) && !visited[to_i][to_j]) { |
| 75 | + dfs(to_i, to_j, count+1, sum + board[si][sj]); |
| 76 | + } |
| 77 | + } |
| 78 | + visited[si][sj] = false; |
| 79 | + } |
| 80 | + |
| 81 | + static boolean isValidPath(int i, int j) { |
| 82 | + return 0 <= i && i < N && 0 <= j && j < M; |
| 83 | + } |
| 84 | +} |
0 commit comments