Advertisement
fit_max

Matrix Max Sum (80%)

Dec 6th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class Testing2 {
  4.  
  5. public static int determineEndCol(int input) {
  6. return Math.abs(input) - 1;
  7. }
  8.  
  9. public static int determineEndRow(int input, int len) {
  10. if (input > 0) {
  11. return 0;
  12. }
  13. return len - 1;
  14. }
  15.  
  16. public static int determineStartCol(int input, int len) {
  17. if (input > 0) {
  18. return 0;
  19. }
  20. return len - 1;
  21. }
  22.  
  23. public static int determineStartRow(int input) {
  24. return Math.abs(input) - 1;
  25. }
  26.  
  27. public static int[][] matrix;
  28.  
  29. public static void main(String[] args) {
  30. Scanner in = new Scanner(System.in);
  31. int N = in.nextInt();
  32. matrix = new int[N][];
  33. in.nextLine();
  34. for (int i = 0; i < matrix.length; i++) {
  35. String[] text = in.nextLine().split(" ");
  36. matrix[i] = new int[text.length];
  37. for (int j = 0; j < matrix[i].length; j++) {
  38. matrix[i][j] = Integer.parseInt(text[j]);
  39. }
  40. }
  41. String[] mask = in.nextLine().split(" ");
  42. int[] pairs = new int[mask.length];
  43. for (int i = 0; i < pairs.length; i++) {
  44. pairs[i] = Integer.parseInt(mask[i]);
  45. }
  46. long biggest = Long.MIN_VALUE;
  47.  
  48. for (int i = 0; i < pairs.length; i += 2) {
  49. int row = determineStartRow(pairs[i]);
  50. int col = determineStartCol(pairs[i+1], matrix[0].length);
  51. int endRow = determineEndRow(pairs[i], matrix.length);
  52. int endCol = determineEndCol(pairs[i+1]);
  53. // long current = getSum(row, col, endRow, endCol);
  54. long current = 0;
  55. do {
  56. current += matrix[row][col];
  57. if (col != endCol) {
  58. if (col < endCol) {
  59. ++col;
  60. } else if (col > endCol) {
  61. --col;
  62. }
  63. }else {
  64. if (row < endRow) {
  65. ++row;
  66. } else if (row > endRow) {
  67. --row;
  68. }
  69. }
  70. }while (row != endRow || col != endCol);
  71. current += matrix[row][col];
  72. if (current > biggest) {
  73. biggest = current;
  74. }
  75. }
  76. System.out.println(biggest);
  77. }
  78.  
  79. public static long getSum(int row, int col, int endR, int endC) {
  80. if (row == endR && col == endC) {
  81. return matrix[row][col];
  82. }
  83.  
  84. if (col < endC) {
  85. return matrix[row][col] + getSum(row, col + 1, endR, endC);
  86. } else if (col > endC) {
  87. return matrix[row][col] + getSum(row, col - 1, endR, endC);
  88. }
  89. if (row < endR) {
  90. return matrix[row][col] + getSum(row + 1, col, endR, endC);
  91. }
  92. return matrix[row][col] + getSum(row - 1, col, endR, endC);
  93. }
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement