Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- class Main {
- public static void main(String[] args) {
- Scanner sc = new Scanner(System.in);
- int n = sc.nextInt();
- int m = sc.nextInt();
- int[][] map = new int[n][m];
- for (int a = 0; a < n; a++) {
- for (int b = 0; b < m; b++) {
- map[a][b] = sc.nextInt();
- }
- }
- int[][] answer = new int[n][m];
- for (int a = 0; a < n; a++) {
- for (int b = 0; b < m; b++) {
- int count = 1;
- answer[a][b] = Math.max(dfs(a, b, count, n, m, map, 0), t(a, b, n, m, map));
- }
- }
- int finalanswer = 0;
- for (int a = 0; a < n; a++) {
- for (int b = 0; b < m; b++) {
- finalanswer = Math.max(finalanswer, answer[a][b]);
- }
- }
- System.out.println(finalanswer);
- sc.close();
- }
- private static int t(int a, int b, int n, int m, int[][] map) {
- int candidate1 = 0;
- int candidate2 = 0;
- int candidate3 = 0;
- int candidate4 = 0;
- if (b - 1 >= 0 && b + 1 < m && a + 1 < n) {
- candidate1 = map[a][b - 1] + map[a][b] + map[a][b + 1] + map[a + 1][b];
- }
- if (b - 1 >= 0 && b + 1 < m && a - 1 >= 0) {
- candidate2 = map[a][b - 1] + map[a][b] + map[a][b + 1] + map[a - 1][b];
- }
- if (b - 1 >= 0 && a - 1 >= 0 && a + 1 < n) {
- candidate3 = map[a][b - 1] + map[a][b] + map[a - 1][b] + map[a + 1][b];
- }
- if (a - 1 >= 0 && b + 1 < m && a + 1 < n) {
- candidate4 = map[a][b + 1] + map[a][b] + map[a - 1][b] + map[a + 1][b];
- }
- return Math.max(Math.max(candidate1, candidate2), Math.max(candidate3, candidate4));
- }
- private static int dfs(int a, int b, int count, int n, int m, int[][] map, int direction) {
- if (count == 4) {
- return map[a][b];
- } else {
- int candidate1 = map[a][b];
- int candidate2 = map[a][b];
- int candidate3 = map[a][b];
- int candidate4 = map[a][b];
- if (b + 1 < m && direction != 1) {
- candidate1 += dfs(a, b + 1, count + 1, n, m, map, 3);
- } else {
- candidate1 = 0;
- }
- if (a + 1 < n && direction != 2) {
- candidate2 += dfs(a + 1, b, count + 1, n, m, map, 4);
- } else {
- candidate2 = 0;
- }
- if (b - 1 >= 0 && direction != 3) {
- candidate3 += dfs(a, b - 1, count + 1, n, m, map, 1);
- } else {
- candidate3 = 0;
- }
- if (a - 1 >= 0 && direction != 4) {
- candidate4 += dfs(a - 1, b, count + 1, n, m, map, 2);
- } else {
- candidate4 = 0;
- }
- return Math.max(Math.max(candidate1, candidate2), Math.max(candidate3, candidate4));
- }
- }
- }
Add Comment
Please, Sign In to add comment