rishu110067

Untitled

Feb 11th, 2022 (edited)
741
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. // Finds the length of the longest path from source to destination.
  2.  
  3. import java.io.*;
  4.  
  5. public class Solution {
  6.     static int globalLongest = 0;
  7.     static int longestPath(int[][] maze, int startX, int startY, int targetX, int targetY) {
  8.         dfs(maze, startX, startY, targetX, targetY, 1);
  9.         return globalLongest;
  10.     }
  11.  
  12.     static void dfs(int[][] maze, int x, int y, int targetX, int targetY, int longest){
  13.         maze[x][y] = 1;
  14.  
  15.         if(x == targetX && y == targetY) {
  16.             if(globalLongest < longest) {
  17.                 globalLongest = longest;
  18.             }
  19.             maze[x][y] = 0;
  20.             return;
  21.         }
  22.  
  23.         if(x + 1 <  maze.length && maze[x+1][y] == 0)
  24.             dfs(maze, x+1, y,  targetX, targetY, longest + 1);
  25.        
  26.         if(x - 1 >=  0 && maze[x-1][y] == 0)
  27.             dfs(maze, x-1, y,  targetX, targetY, longest + 1);
  28.        
  29.         if(y + 1 <  maze[0].length && maze[x][y+1] == 0)
  30.             dfs(maze, x, y+1,  targetX, targetY, longest + 1);
  31.        
  32.         if(y - 1 >=  0 && maze[x][y - 1] == 0)
  33.             dfs(maze, x, y-1,  targetX, targetY, longest + 1);
  34.        
  35.         maze[x][y] = 0;
  36.     }
  37.  
  38.     public static void main(String[] args) {
  39.         int[][] maze = new int[5][7];
  40.         maze[0] = new int[]{0,0,0,0,0,0,0};
  41.         maze[1] = new int[]{0,1,0,0,1,0,0};
  42.         maze[2] = new int[]{1,0,0,1,0,0,0};
  43.         maze[3] = new int[]{0,0,0,0,0,0,0};
  44.         maze[4] = new int[]{0,1,0,0,0,1,0};
  45.  
  46.         System.out.println(longestPath(maze, 0, 1, 3, 5));
  47.     }
  48. }
Add Comment
Please, Sign In to add comment