1. You are given a number n and a number m representing number of rows and columns in a maze.
2. You are standing in the top-left corner and have to reach the bottom-right corner.Input Format
3. In a single move you are allowed to jump 1 or more steps horizontally (as h1, h2, .. ), or 1 or more steps vertically (as v1, v2, ..) or 1 or more steps diagonally (as d1, d2, ..).
4. Complete the body of getMazePath function - without changing signature - to get the list of all paths that can be used to move from top-left to bottom-right.
Use sample input and output to take idea about output.
A number nOutput Format
A number m
Contents of the arraylist containing paths as shown in sample output
Constraints
0 <= n <= 10
0 <= m <= 10
Sample Input
2
2
Sample Output
[h1v1, v1h1, d1]
Solution:
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(), m = sc.nextInt();
System.out.println(getMazePaths(1,1,m,n));
}
// sr - source row
// sc - source column
// dr - destination row
// dc - destination column
public static ArrayList<String> getMazePaths(int sr, int sc, int dr, int dc) {
ArrayList<String> res = new ArrayList<>();
if(sr > dr || sc > dc)
return res;
if(sr == dr && sc == dc){
res.add("");
return res;
}
for(int i=1;i<=dr-sr;i++){
ArrayList<String> hpath = getMazePaths(sr+i,sc,dr,dc);
for(String s:hpath)
res.add("h"+i+s);
}
for(int j=1;j<=dc-sc;j++){
ArrayList<String> vpath = getMazePaths(sr,sc+j,dr,dc);
for(String s:vpath)
res.add("v"+j+s);
}
for(int d=1;d<=(dr-sr) && d<= (dc-sc);d++){
ArrayList<String> dpath = getMazePaths(sr+d,sc+d,dr,dc);
for(String s:dpath)
res.add("d"+d+s);
}
return res;
}
}
Comments
Post a Comment