Print path from given Source to Destination in 2 | Java program for printing a path from given source to destination ; Function to print the path ; Base condition ; Pop stores elements ; Recursive call for printing stack In reverse order ; Function to store the path into The stack , if path exist ; Base condition ; Push current elements ; Condition to check whether reach to the Destination or not ; Increment ' x ' ordinate of source by ( 2 * x + y ) Keeping ' y ' constant ; Increment ' y ' ordinate of source by ( 2 * y + x ) Keeping ' x ' constant ; Pop current elements form stack ; If no path exists ; Utility function to check whether path exist or not ; To store x co - ordinate ; To store y co - ordinate ; Function to find the path ; Print - 1 , if path doesn 't exist ; Driver code ; Function call
import java . util . * ; class GFG { static void printExistPath ( Stack < Integer > sx , Stack < Integer > sy , int last ) { if ( sx . isEmpty ( ) || sy . isEmpty ( ) ) { return ; } int x = sx . peek ( ) ; int y = sy . peek ( ) ; sx . pop ( ) ; sy . pop ( ) ; printExistPath ( sx , sy , last ) ; if ( sx . size ( ) == last - 1 ) { System . out . print ( " ( " + x + " , ▁ " + y + " ) " ) ; } else { System . out . print ( " ( " + x + " , ▁ " + y + " ) - > " ) ; } } static boolean storePath ( int srcX , int srcY , int destX , int destY , Stack < Integer > sx , Stack < Integer > sy ) { if ( srcX > destX srcY > destY ) { return false ; } sx . add ( srcX ) ; sy . add ( srcY ) ; if ( srcX == destX && srcY == destY ) { printExistPath ( sx , sy , sx . size ( ) ) ; return true ; } if ( storePath ( ( 2 * srcX ) + srcY , srcY , destX , destY , sx , sy ) ) { return true ; } if ( storePath ( srcX , ( 2 * srcY ) + srcX , destX , destY , sx , sy ) ) { return true ; } sx . pop ( ) ; sy . pop ( ) ; return false ; } static boolean isPathExist ( int srcX , int srcY , int destX , int destY ) { Stack < Integer > sx = new Stack < Integer > ( ) ; Stack < Integer > sy = new Stack < Integer > ( ) ; return storePath ( srcX , srcY , destX , destY , sx , sy ) ; } static void printPath ( int srcX , int srcY , int destX , int destY ) { if ( ! isPathExist ( srcX , srcY , destX , destY ) ) { System . out . print ( " - 1" ) ; } } public static void main ( String [ ] args ) { int srcX = 5 , srcY = 8 ; int destX = 83 , destY = 21 ; printPath ( srcX , srcY , destX , destY ) ; } }