Shortest Cycle Containing Target Node - Google Top Interview Questions


Problem Statement :


You are given a two-dimensional list of integers graph representing a directed graph as an adjacency list. You are also given an integer target.

Return the length of a shortest cycle that contains target. If a solution does not exist, return -1.

Constraints

n, m ≤ 250 where n and m are the number of rows and columns in graph


Example 1

Input

Visualize

graph = [

    [1],


    [2],


    [0]


]

target = 0

Output

3

Explanation

The nodes 0 -> 1 -> 2 -> 0 form a cycle




Example 2

Input

Visualize

graph = [

    [1],

    [2],

    [4],

    [],


    [0]

]

target = 3


Output
-1



Solution :



title-img




                        Solution in C++ :

vector<int> color;
vector<long long int> dist;
vector<vector<int>> adj;
int dest;
long long int dfs(int u) {
    if (u == dest) {
        return 0;
    }
    color[u] = 1;  // gray
    long long int mindist = INT_MAX;
    for (int v : adj[u]) {
        if (color[v] == 0) {
            mindist = min(mindist, 1 + dfs(v));
        } else if (color[v] == 2) {
            mindist = min(mindist, 1 + dist[v]);
        }
    }
    color[u] = 2;  // black
    return dist[u] = mindist;
}

int solve(vector<vector<int>>& graph, int target) {
    adj = graph;
    dest = target;
    color.assign(graph.size(), 0);
    dist.assign(graph.size(), 0);
    long long int res = INT_MAX;
    for (int i : graph[target]) {
        res = min(res, 1 + dfs(i));
    }
    if (res == INT_MAX) return -1;
    return res;
}
                    


                        Solution in Java :

import java.util.*;

class Solution {
    public int solve(int[][] graph, int target) {
        boolean[] visited = new boolean[graph.length];
        Queue<Integer> q = new LinkedList<>();
        q.add(target);

        int level = 0;
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                int tmp = q.remove();
                visited[tmp] = true;

                for (int neighbor : graph[tmp]) {
                    if (neighbor == target)
                        return level + 1;
                    else if (!visited[neighbor])
                        q.add(neighbor);
                }
            }

            level++;
        }

        return -1;
    }
}
                    


                        Solution in Python : 
                            
class Solution:
    def solve(self, graph, target):
        visited = set()
        layer = [target]
        length = 0

        while layer:
            length += 1
            next_layer = []
            for u in layer:
                for v in graph[u]:
                    if v == target:
                        return length
                    if v in visited:
                        continue
                    visited.add(v)
                    next_layer.append(v)
            layer = next_layer

        return -1
                    


View More Similar Problems

Inserting a Node Into a Sorted Doubly Linked List

Given a reference to the head of a doubly-linked list and an integer ,data , create a new DoublyLinkedListNode object having data value data and insert it at the proper location to maintain the sort. Example head refers to the list 1 <-> 2 <-> 4 - > NULL. data = 3 Return a reference to the new list: 1 <-> 2 <-> 4 - > NULL , Function Description Complete the sortedInsert function

View Solution →

Reverse a doubly linked list

This challenge is part of a tutorial track by MyCodeSchool Given the pointer to the head node of a doubly linked list, reverse the order of the nodes in place. That is, change the next and prev pointers of the nodes so that the direction of the list is reversed. Return a reference to the head node of the reversed list. Note: The head node might be NULL to indicate that the list is empty.

View Solution →

Tree: Preorder Traversal

Complete the preorder function in the editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's preorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the preOrder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the tree's

View Solution →

Tree: Postorder Traversal

Complete the postorder function in the editor below. It received 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's postorder traversal as a single line of space-separated values. Input Format Our test code passes the root node of a binary tree to the postorder function. Constraints 1 <= Nodes in the tree <= 500 Output Format Print the

View Solution →

Tree: Inorder Traversal

In this challenge, you are required to implement inorder traversal of a tree. Complete the inorder function in your editor below, which has 1 parameter: a pointer to the root of a binary tree. It must print the values in the tree's inorder traversal as a single line of space-separated values. Input Format Our hidden tester code passes the root node of a binary tree to your $inOrder* func

View Solution →

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →