Advertisement
rishu110067

Untitled

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