Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.InputStreamReader;
- public class Portali {
- public static void main(String[] args) throws IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String[] inpStart = br.readLine().split(" ");
- int startRow = Integer.parseInt(inpStart[0]);
- int startCol = Integer.parseInt(inpStart[1]);
- String[] inpSize = br.readLine().split(" ");
- int rows = Integer.parseInt(inpSize[0]);
- int cols = Integer.parseInt(inpSize[1]);
- int[][] matrix = new int[rows][cols];
- for (int i = 0; i < rows ; i++) {
- String[] temp = br.readLine().split(" ");
- for (int j = 0; j < cols ; j++) {
- if (temp[j].equals("#")) {
- matrix[i][j] = -1;
- } else {
- matrix[i][j] = Integer.parseInt(temp[j]);
- }
- }
- }
- printMatrix(matrix);
- int[] maxi = new int[1];
- boolean[][] visited = new boolean[rows][cols];
- dfs(matrix, visited, maxi, startRow, startCol, 0, 0);
- System.out.println(maxi[0]);
- }
- private static void dfs(int[][] matrix, boolean[][] visited, int[] max, int row, int col, int current, int previousValue) {
- if (row < 0 || col < 0 || row >= matrix.length || col >= matrix[0].length) {
- current -= previousValue;
- max[0] = Math.max(max[0], current);
- return;
- }
- int value = matrix[row][col];
- if (visited[row][col] || value < 0) {
- current -= previousValue;
- max[0] = Math.max(max[0], current);
- return;
- }
- current += value;
- visited[row][col] = true;
- dfs(matrix, visited, max, row + value, col, current, value);
- dfs(matrix, visited, max, row - value, col, current, value);
- dfs(matrix, visited, max, row, col + value, current, value);
- dfs(matrix, visited, max, row, col - value, current, value);
- visited[row][col] = false;
- current -= previousValue;
- max[0] = Math.max(max[0], current);
- }
- private static void printMatrix(int[][] matrix) {
- System.out.println();
- for (int i = 0; i < matrix.length; i++) {
- for (int j = 0; j < matrix[0].length; j++) {
- System.out.print(matrix[i][j] + " ");
- }
- System.out.println();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement