|
| 1 | +```java |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | + |
| 5 | +public class Main { |
| 6 | + |
| 7 | + static int n, m; |
| 8 | + static int[][] board; |
| 9 | + static boolean[][] visited; |
| 10 | + static int max = 0; |
| 11 | + |
| 12 | + static final int[][] dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; |
| 13 | + |
| 14 | + public static void main(String[] args) throws Exception { |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + StringTokenizer st; |
| 17 | + |
| 18 | + st = new StringTokenizer(br.readLine()); |
| 19 | + n = Integer.parseInt(st.nextToken()); |
| 20 | + m = Integer.parseInt(st.nextToken()); |
| 21 | + board = new int[n][m]; |
| 22 | + visited = new boolean[n][m]; |
| 23 | + |
| 24 | + for (int r = 0; r < n; r++) { |
| 25 | + st = new StringTokenizer(br.readLine()); |
| 26 | + for (int c = 0; c < m; c++) { |
| 27 | + board[r][c] = Integer.parseInt(st.nextToken()); |
| 28 | + } |
| 29 | + } |
| 30 | + |
| 31 | + for (int r = 0; r < n; r++) { |
| 32 | + for (int c = 0; c < m; c++) { |
| 33 | + visited[r][c] = true; |
| 34 | + dfs(r, c, board[r][c], 1); |
| 35 | + visited[r][c] = false; |
| 36 | + |
| 37 | + chkother(r, c); |
| 38 | + } |
| 39 | + } |
| 40 | + |
| 41 | + System.out.println(max); |
| 42 | + } |
| 43 | + |
| 44 | + static void dfs(int x, int y, int sum, int depth) { |
| 45 | + if (depth == 4) { |
| 46 | + max = Math.max(max, sum); |
| 47 | + return; |
| 48 | + } |
| 49 | + |
| 50 | + for (int d = 0; d < 4; d++) { |
| 51 | + int nx = x + dir[d][0]; |
| 52 | + int ny = y + dir[d][1]; |
| 53 | + |
| 54 | + if (nx < 0 || ny < 0 || nx >= n || ny >= m || visited[nx][ny]) continue; |
| 55 | + |
| 56 | + visited[nx][ny] = true; |
| 57 | + dfs(nx, ny, sum + board[nx][ny], depth + 1); |
| 58 | + visited[nx][ny] = false; |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + static void chkother(int x, int y) { |
| 63 | + int wing = 0; |
| 64 | + int min = Integer.MAX_VALUE; |
| 65 | + int sum = board[x][y]; |
| 66 | + |
| 67 | + for (int d = 0; d < 4; d++) { |
| 68 | + int nx = x + dir[d][0]; |
| 69 | + int ny = y + dir[d][1]; |
| 70 | + |
| 71 | + if (nx < 0 || ny < 0 || nx >= n || ny >= m) continue; |
| 72 | + wing++; |
| 73 | + sum += board[nx][ny]; |
| 74 | + min = Math.min(min, board[nx][ny]); |
| 75 | + } |
| 76 | + |
| 77 | + if (wing < 3) return; |
| 78 | + if (wing == 4) sum -= min; |
| 79 | + max = Math.max(max, sum); |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +``` |
0 commit comments