Guest User

Untitled

a guest
Mar 17th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. class Main {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int n = sc.nextInt();
  7. int m = sc.nextInt();
  8. int[][] map = new int[n][m];
  9. for (int a = 0; a < n; a++) {
  10. for (int b = 0; b < m; b++) {
  11. map[a][b] = sc.nextInt();
  12. }
  13. }
  14. int[][] answer = new int[n][m];
  15. for (int a = 0; a < n; a++) {
  16. for (int b = 0; b < m; b++) {
  17. int count = 1;
  18. answer[a][b] = Math.max(dfs(a, b, count, n, m, map, 0), t(a, b, n, m, map));
  19. }
  20. }
  21. int finalanswer = 0;
  22. for (int a = 0; a < n; a++) {
  23. for (int b = 0; b < m; b++) {
  24. finalanswer = Math.max(finalanswer, answer[a][b]);
  25. }
  26. }
  27. System.out.println(finalanswer);
  28. sc.close();
  29. }
  30.  
  31. private static int t(int a, int b, int n, int m, int[][] map) {
  32. int candidate1 = 0;
  33. int candidate2 = 0;
  34. int candidate3 = 0;
  35. int candidate4 = 0;
  36. if (b - 1 >= 0 && b + 1 < m && a + 1 < n) {
  37. candidate1 = map[a][b - 1] + map[a][b] + map[a][b + 1] + map[a + 1][b];
  38. }
  39. if (b - 1 >= 0 && b + 1 < m && a - 1 >= 0) {
  40. candidate2 = map[a][b - 1] + map[a][b] + map[a][b + 1] + map[a - 1][b];
  41. }
  42. if (b - 1 >= 0 && a - 1 >= 0 && a + 1 < n) {
  43. candidate3 = map[a][b - 1] + map[a][b] + map[a - 1][b] + map[a + 1][b];
  44. }
  45. if (a - 1 >= 0 && b + 1 < m && a + 1 < n) {
  46. candidate4 = map[a][b + 1] + map[a][b] + map[a - 1][b] + map[a + 1][b];
  47. }
  48. return Math.max(Math.max(candidate1, candidate2), Math.max(candidate3, candidate4));
  49. }
  50.  
  51. private static int dfs(int a, int b, int count, int n, int m, int[][] map, int direction) {
  52. if (count == 4) {
  53. return map[a][b];
  54. } else {
  55. int candidate1 = map[a][b];
  56. int candidate2 = map[a][b];
  57. int candidate3 = map[a][b];
  58. int candidate4 = map[a][b];
  59. if (b + 1 < m && direction != 1) {
  60. candidate1 += dfs(a, b + 1, count + 1, n, m, map, 3);
  61. } else {
  62. candidate1 = 0;
  63. }
  64. if (a + 1 < n && direction != 2) {
  65. candidate2 += dfs(a + 1, b, count + 1, n, m, map, 4);
  66. } else {
  67. candidate2 = 0;
  68. }
  69. if (b - 1 >= 0 && direction != 3) {
  70. candidate3 += dfs(a, b - 1, count + 1, n, m, map, 1);
  71. } else {
  72. candidate3 = 0;
  73. }
  74. if (a - 1 >= 0 && direction != 4) {
  75. candidate4 += dfs(a - 1, b, count + 1, n, m, map, 2);
  76. } else {
  77. candidate4 = 0;
  78. }
  79. return Math.max(Math.max(candidate1, candidate2), Math.max(candidate3, candidate4));
  80. }
  81. }
  82. }
Add Comment
Please, Sign In to add comment