|
| 1 | +``` |
| 2 | +import java.io.*; |
| 3 | +import java.util.*; |
| 4 | +
|
| 5 | +public class Main { |
| 6 | + static int N, M; |
| 7 | + static int[][] board; |
| 8 | + static boolean[][] visited; |
| 9 | + static int maxScore = 0; |
| 10 | +
|
| 11 | + public static void main(String[] args) throws IOException { |
| 12 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 13 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 14 | +
|
| 15 | + N = Integer.parseInt(st.nextToken()); |
| 16 | + M = Integer.parseInt(st.nextToken()); |
| 17 | + board = new int[N][M]; |
| 18 | + visited = new boolean[N][M]; |
| 19 | +
|
| 20 | + for (int i = 0; i < N; i++) { |
| 21 | + String line = br.readLine(); |
| 22 | + for (int j = 0; j < M; j++) { |
| 23 | + board[i][j] = line.charAt(j) - '0'; |
| 24 | + } |
| 25 | + } |
| 26 | +
|
| 27 | + dfs(0, 0, 0); |
| 28 | + System.out.println(maxScore); |
| 29 | + } |
| 30 | +
|
| 31 | + static void dfs(int r, int c, int sum) { |
| 32 | + if (r >= N) { |
| 33 | + maxScore = Math.max(maxScore, sum); |
| 34 | + return; |
| 35 | + } |
| 36 | +
|
| 37 | + if (c >= M) { |
| 38 | + dfs(r + 1, 0, sum); |
| 39 | + return; |
| 40 | + } |
| 41 | +
|
| 42 | + if (visited[r][c]) { |
| 43 | + dfs(r, c + 1, sum); |
| 44 | + return; |
| 45 | + } |
| 46 | +
|
| 47 | + int current = 0; |
| 48 | + for (int len = 0; c + len < M; len++) { |
| 49 | + if (visited[r][c + len]) break; |
| 50 | +
|
| 51 | + for (int i = 0; i <= len; i++) visited[r][c + i] = true; |
| 52 | + current = current * 10 + board[r][c + len]; |
| 53 | + |
| 54 | + dfs(r, c + len + 1, sum + current); |
| 55 | + |
| 56 | + for (int i = 0; i <= len; i++) visited[r][c + i] = false; |
| 57 | + } |
| 58 | +
|
| 59 | + current = board[r][c]; |
| 60 | + for (int len = 1; r + len < N; len++) { |
| 61 | + if (visited[r + len][c]) break; |
| 62 | +
|
| 63 | + for (int i = 1; i <= len; i++) visited[r + i][c] = true; |
| 64 | + |
| 65 | + int tempVal = 0; |
| 66 | + for (int i = 0; i <= len; i++) { |
| 67 | + tempVal = tempVal * 10 + board[r + i][c]; |
| 68 | + } |
| 69 | + |
| 70 | + dfs(r, c + 1, sum + tempVal); |
| 71 | + |
| 72 | + for (int i = 1; i <= len; i++) visited[r + i][c] = false; |
| 73 | + } |
| 74 | + } |
| 75 | +} |
| 76 | +``` |
0 commit comments