Related Articles

# Shortest path for a thief to reach the Nth house avoiding policemen

• Last Updated : 23 May, 2021

Given an unweighted graph and a boolean array A[ ], where if the ith index of array A[ ] denotes if that node can can be visited (0) or not (1). The task is to find the shortest path to reach (N – 1)th node from the 0th node. If it is not possible to reach, print -1.

Examples :

Input : N = 5, A[] = {0, 1, 0, 0, 0}, Edges = {{0, 1}, {0, 2}, {1, 4}, {2, 3}, {3, 4}}
Output: 3
Explanation: There are two paths from 0th house to 4th house

• 0 → 1 → 4
• 0 →2 → 3 → 4

Since a policeman is present at the 1st house, the only path that can be chosen is the 2nd path.

Input : N = 4, A = {0, 1, 1, 0}, Edges = {{0, 1}, {0, 2}, {1, 3}, {2, 3}}
Output : -1

Approach: This problem is similar to finding the shortest path in an unweighted graph. Therefore, the problem can be solved using BFS.

Follow the steps below to solve the problem:

• Initialize an unordered_map, say adj to store the edges. The edge (a, b) must be excluded if there is a policeman either at node a or at node b.
• Initialize a variable, pathLength = 0.
• Initialize a vector of the boolean data type, say visited, to store whether a node is visited or not.
• Initialize an arraydist[0, 1, …., v-1] such that dist[i] stores the distance of vertex i from the root vertex
• Initialize a queue and push node 0 in it. Also, mark node 0 as visited.
• Iterate while the queue is not empty and the node N – 1 is not visited, pop the front element from the queue, and push all the elements into the queue that have an edge from the front element of the queue and are not visited and increase the distance of all these nodes by 1 + dist[q.top()].
• If the node (N – 1) is not visited, then print -1.
• Otherwise, print the distance of (N – 1)th node from the root node.

Below is the implementation of the above approach:

## C++

 `// C++ program for the above approach`` ` `#include ``using` `namespace` `std;`` ` `// Function to create graph edges``// where node A and B can be visited``void` `createGraph(unordered_map<``int``, vector<``int``> >& adj,``                 ``int` `paths[], ``int` `A[], ``int` `N, ``int` `E)``{``    ``// Visit all the connections``    ``for` `(``int` `i = 0; i < E; i++) {`` ` `        ``// If a policeman is at any point of``        ``// connection, leave that connection.``        ``// Insert the connect otherwise.``        ``if` `(!A[paths[i]] && !A[paths[i]]) {`` ` `            ``adj[paths[i]].push_back(paths[i]);``        ``}``    ``}``}`` ` `// Function to find the shortest path``int` `minPath(``int` `paths[], ``int` `A[],``            ``int` `N, ``int` `E)``{``    ``// If police is at either at``    ``// the 1-st house or at N-th house``    ``if` `(A == 1 || A[N - 1] == 1)`` ` `        ``// The thief cannot reach``        ``// the N-th house``        ``return` `-1;`` ` `    ``// Stores Edges of graph``    ``unordered_map<``int``, vector<``int``> > adj;`` ` `    ``// Function call to store connections``    ``createGraph(adj, paths, A, N, E);`` ` `    ``// Stores wheather node is``    ``// visited or not``    ``vector<``int``> visited(N, 0);`` ` `    ``// Stores distances``    ``// from the root node``    ``int` `dist[N];``    ``dist = 0;`` ` `    ``queue<``int``> q;``    ``q.push(0);``    ``visited = 1;`` ` `    ``// Visit all nodes that are``    ``// currently in the queue``    ``while` `(!q.empty()) {`` ` `        ``int` `temp = q.front();``        ``q.pop();`` ` `        ``for` `(``auto` `x : adj[temp]) {`` ` `            ``// If current node is``            ``// not visited already``            ``if` `(!visited[x]) {`` ` `                ``q.push(x);``                ``visited[x] = 1;``                ``dist[x] = dist[temp] + 1;``            ``}``        ``}``    ``}`` ` `    ``if` `(!visited[N - 1])``        ``return` `-1;``    ``else``        ``return` `dist[N - 1];``}`` ` `// Driver Code``int` `main()``{``    ``// N : Number of houses``    ``// E: Number of edges``    ``int` `N = 5, E = 5;`` ` `    ``// Given positions``    ``int` `A[] = { 0, 1, 0, 0, 0 };`` ` `    ``// Given Paths``    ``int` `paths[] = { { 0, 1 },``                       ``{ 0, 2 },``                       ``{ 1, 4 },``                       ``{ 2, 3 },``                       ``{ 3, 4 } };`` ` `    ``// Function call``    ``cout << minPath(paths, A, N, E);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.io.*;``import` `java.lang.*;``import` `java.util.*;`` ` `public` `class` `GFG {`` ` `    ``// Function to create graph edges``    ``// where node A and B can be visited``    ``static` `void``    ``createGraph(HashMap > adj,``                ``int` `paths[][], ``int` `A[], ``int` `N, ``int` `E)``    ``{``        ``// Visit all the connections``        ``for` `(``int` `i = ``0``; i < E; i++) {`` ` `            ``// If a policeman is at any point of``            ``// connection, leave that connection.``            ``// Insert the connect otherwise.``            ``if` `(A[paths[i][``0``]] != ``1``                ``&& A[paths[i][``1``]] != ``1``) {``                ``ArrayList list = adj.getOrDefault(``                    ``paths[i][``0``], ``new` `ArrayList<>());``                ``list.add(paths[i][``1``]);``                ``adj.put(paths[i][``0``], list);``            ``}``        ``}``    ``}`` ` `    ``// Function to find the shortest path``    ``static` `int` `minPath(``int` `paths[][], ``int` `A[], ``int` `N, ``int` `E)``    ``{``        ``// If police is at either at``        ``// the 1-st house or at N-th house``        ``if` `(A[``0``] == ``1` `|| A[N - ``1``] == ``1``)`` ` `            ``// The thief cannot reach``            ``// the N-th house``            ``return` `-``1``;`` ` `        ``// Stores Edges of graph``        ``HashMap > adj``            ``= ``new` `HashMap<>();`` ` `        ``// Function call to store connections``        ``createGraph(adj, paths, A, N, E);`` ` `        ``// Stores wheather node is``        ``// visited or not``        ``boolean` `visited[] = ``new` `boolean``[N];`` ` `        ``// Stores distances``        ``// from the root node``        ``int` `dist[] = ``new` `int``[N];``        ``dist[``0``] = ``0``;`` ` `        ``ArrayDeque q = ``new` `ArrayDeque<>();``        ``q.addLast(``0``);``        ``visited[``0``] = ``true``;`` ` `        ``// Visit all nodes that are``        ``// currently in the queue``        ``while` `(!q.isEmpty()) {`` ` `            ``int` `temp = q.removeFirst();`` ` `            ``for` `(``int` `x : adj.getOrDefault(``                     ``temp, ``new` `ArrayList<>())) {`` ` `                ``// If current node is``                ``// not visited already``                ``if` `(!visited[x]) {`` ` `                    ``q.addLast(x);``                    ``visited[x] = ``true``;``                    ``dist[x] = dist[temp] + ``1``;``                ``}``            ``}``        ``}`` ` `        ``if` `(!visited[N - ``1``])``            ``return` `-``1``;``        ``else``            ``return` `dist[N - ``1``];``    ``}`` ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{`` ` `        ``// N : Number of houses``        ``// E: Number of edges``        ``int` `N = ``5``, E = ``5``;`` ` `        ``// Given positions``        ``int` `A[] = { ``0``, ``1``, ``0``, ``0``, ``0` `};`` ` `        ``// Given Paths``        ``int` `paths[][] = {``            ``{ ``0``, ``1` `}, { ``0``, ``2` `}, { ``1``, ``4` `}, { ``2``, ``3` `}, { ``3``, ``4` `}``        ``};`` ` `        ``// Function call``        ``System.out.print(minPath(paths, A, N, E));``    ``}``}`` ` `// This code is contributed by Kingash.`

Output:
`3`

Time complexity: O (N + E)
Auxiliary Space: O (N + E)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up