My code has got submitted but I have a doubt.
Following is my complete code which got submitted.
import java.util.*;
class Graphs {
private class Vertex {
HashMap<Integer, Character> neighbour;
Vertex () {
neighbour=new HashMap<Integer, Character>();
}
}
private HashMap<Integer, Vertex> graph;
Graphs () {
graph=new HashMap<Integer, Vertex>();
}
public void addVertex (int vname) {
Vertex v=new Vertex();
graph.put(vname, v);
}
public void addEdge (int vname1, int vname2, char cost) {
if (!graph.containsKey(vname1) || !graph.containsKey(vname2) || graph.get(vname1).neighbour.containsKey(vname2)) {
return;
}
Vertex v1=graph.get(vname1);
Vertex v2=graph.get(vname2);
v1.neighbour.put(vname2, cost);
v2.neighbour.put(vname1,cost);
}
public boolean containsVertex (int vname) {
return graph.containsKey(vname);
}
public Pair getPair (int vname) {
Vertex v=graph.get(vname);
ArrayList<Integer> list=new ArrayList<>(v.neighbour.keySet());
int val=list.get(0);
char ch=v.neighbour.get(val);
Pair pair=new Pair ();
pair.ver=val;
pair.c=ch;
return pair;
}
}
class Pair {
int ver;
char c;
}
public class Main {
public static void main(String args[]) {
Scanner sc=new Scanner (System.in);
int t=sc.nextInt();
while (t-->0) {
Graphs graph=new Graphs();
int n=sc.nextInt();
int l=sc.nextInt();
int s=sc.nextInt();
int x,y;
for (int i=0; i<l; i++) {
x=sc.nextInt();
y=sc.nextInt();
graph.addVertex (x);
graph.addVertex (y);
graph.addEdge (x,y,'l');
}
for (int i=0; i<s; i++) {
x=sc.nextInt();
y=sc.nextInt();
graph.addVertex (x);
graph.addVertex (y);
graph.addEdge (x,y,'s');
}
System.out.println (minMoves (graph, n, 1));
}
}
static int minMoves (Graphs graph, int n, int i) {
if (i==n) {
return 1;
} else if (i>n) {
return 0;
} else {
int temp=i;
if (graph.containsVertex (i)) {
Pair pair=graph.getPair (i);
if (pair.ver>i && pair.c=='l'){
temp=pair.ver;
}
}
int min=Integer.MAX_VALUE;
for (int j=1; j<=6; j++) {
min=Math.min (min, minMoves (graph, n, temp + j));
}
return 1+ min;
}
}
}
In the recursive function ( if part where getPair function is used ) I have worked for the ladder condition then only my code got executed. But whenever I put snake condition it shows stack overflow.
Following is the code when I use snake condition.
static int minMoves (Graphs graph, int n, int i) {
if (i==n) {
return 1;
} else if (i>n) {
return 0;
} else {
int temp=i;
if (graph.containsVertex (i)) {
Pair pair=graph.getPair (i);
if ((pair.ver>i && pair.c=='l') || (pair.c=='s' && pair.ver<i)){
temp=pair.ver;
}
}
int min=Integer.MAX_VALUE;
for (int j=1; j<=6; j++) {
min=Math.min (min, minMoves (graph, n, temp + j));
}
return 1+ min;
}
}
Please tell me where the condition is causing error. I have tried so much to detect the error.