Vivek Singh
1 min readJun 22, 2021

--

Changed your code to cater for parallel edge

```

/*

mark visited edge

*/

public class Solution {

Map<Integer, List<Integer>> graph = new HashMap<>();

public boolean leadsToDestination(int n, int[][] edges, int source, int destination) {

buildGraph(graph, edges);

Queue<Pair<Integer,Integer>> q = new LinkedList<>();

q.add(new Pair(-1,source));

Set<Pair<Integer,Integer>> visited = new HashSet<>();

while (!q.isEmpty()) {

Pair<Integer,Integer> edge = q.poll();

int node = edge.getValue();

if (node == destination) {

//destination was not been added since it is the end

// there was no edge from destination

if (!graph.containsKey(node))//check path is the end or not

continue;

}

visited.add(edge);

// if node is the end but was not the destination, it is not a path

if (!graph.containsKey(node)) // Check if the current visiting node is at the end of the path

return false;

for (int next : graph.get(node)) {

edge = new Pair(node,next);//from->to

//there is any loop or not

if (!visited.contains(edge))

q.add(edge);

else

return false;

}

}

return true;

}

private void buildGraph(Map<Integer, List<Integer>> graph, int[][] edges) {

for (int[] edge : edges) {

int src = edge[0];

int des = edge[1];

graph.compute(src, (k, v) -> v == null ? new ArrayList<>() : v).add(des);

}

}

}

```

--

--

Vivek Singh
Vivek Singh

No responses yet