Find the nearest clone

Sort by

recency

|

189 Discussions

|

  • + 1 comment

    What the **** is the need for the variable val?

  • + 0 comments

    Python

    def findShortest(graph_nodes, graph_from, graph_to, ids, val):
        graph = defaultdict(set)
        for start, end in zip(graph_from, graph_to):
            graph[start].add(end)
            graph[end].add(start)
        
        min_path_len = math.inf
        for node, node_color in enumerate(ids, start=1):
            if node_color != val:
                continue
            visited = set([node])
            queue = deque(graph[node])
            curr_path_len = 0
            found_at = None
            while queue:
                curr = queue.popleft()
                if curr in visited:
                    continue
                visited.add(curr)
                curr_path_len += 1
                curr_color = ids[curr-1]
                if curr_color == node_color:
                    found_at = curr_path_len
                    break
                queue.extend(graph[curr])
            if found_at:
                min_path_len = min(min_path_len, found_at)
        if min_path_len == math.inf:
            return -1
        return min_path_len
    
  • + 0 comments

    javascript

    function findShortest(graphNodes, graphFrom, graphTo, ids, val) {
      let map = new Map()
      for (let i = 0; i < graphFrom.length; i++) {
        if (!map.has(graphFrom[i])) map.set(graphFrom[i], [])
        map.get(graphFrom[i]).push(graphTo[i])
        if (!map.has(graphTo[i])) map.set(graphTo[i], [])
        map.get(graphTo[i]).push(graphFrom[i])
      }
    
      let nodesToInvestigate = []
      for (let i = 1; i <= ids.length; i++) {
        if (ids[i - 1] == val) nodesToInvestigate.push(i)
      }
    
      if (nodesToInvestigate.length < 2) return -1
    
      let visited = new Set(), distances = []
      for (let i = 0; i < nodesToInvestigate.length; i++) {
        let queue = [[nodesToInvestigate[i], 0]]
        visited.add(nodesToInvestigate[i])
        while (queue.length > 0) {
          let [cur, steps] = queue.shift()
          visited.add(cur)
          if (ids[cur - 1] == val && cur != nodesToInvestigate[i]) {
            distances.push(steps)
            continue
          }
          queue.push(...map.get(cur).filter(to => !visited.has(to))
            .map(node => [node, steps + 1]))
        }
      }
      return Math.min(...distances)
    }
    
  • + 1 comment

    Test Case 12 has no answer and is the wrong expected output. There is no edge linking the nodes with colour 2 in the graph.

  • + 0 comments

    !/bin/python3

    import math import os import random import re import sys from collections import defaultdict

    This class represents a directed graph

    using adjacency list representation

    class Graph:

    # Constructor
    def __init__(self):
    
        # Default dictionary to store graph
        self.graph = defaultdict(list)
    
    # Function to add an edge to graph
    def addEdge(self, u, v):
        self.graph[u].append(v)
    
    # Function to print a BFS of graph
    def BFS(self, s):
        dico = dict()
        # Mark all the vertices as not visited
        visited = [False] * (max(self.graph) + 1)
        # Create a queue for BFS
        queue = []
        queue0 = []
        # Mark the source node as
        # visited and enqueue it
        if (s not in self.graph):
            print(-1)
            dico[s]=-1
            return dico
        queue.append(s)
        queue0.append(0)
        visited[s] = True
        cmpt=1
        l=[0]
        k=0
        dico = dict()
        while queue:
    
            # Dequeue a vertex from
            # queue and print it
            s = queue.pop(0)
            print(s,end=" ")
            #s0=queue0.pop(0)
            print(l[k]*cmpt)
            dico[s]=l[k]*cmpt
            k+=1
    
    
    
            # Get all adjacent vertices of the
            # dequeued vertex s.
            # If an adjacent has not been visited,
            # then mark it visited and enqueue it
            maxp=max(l)
            for i in self.graph[s]:
                if visited[i] == False:
                    l.append(maxp+1)
                    queue.append(i)
                    visited[i] = True
        return dico
    

    Complete the findShortest function below.

    #

    For the weighted graph, :

    #

    1. The number of nodes is _nodes.

    2. The number of edges is _edges.

    3. An edge exists between _from[i] to _to[i].

    # # def findShortest(graph_nodes, graph_from, graph_to, ids, val): # solve here n= graph_nodes g = Graph() for i in range(len(graph_from)): g.addEdge(graph_from[i],graph_to[i]) g.addEdge(graph_to[i],graph_from[i]) if ids.count(val)<=1: return -1 dico = g.BFS(val) for i in range(1,n+1): if i not in dico.keys(): dico[i]=g.BFS(i)[i] s=[] for k in range(len(ids)): if ids[k]==2 and dico[k+1]>0: s.append(dico[k+1]) print(s)

    return min(s)
    

    if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')

    graph_nodes, graph_edges = map(int, input().split())
    
    graph_from = [0] * graph_edges
    graph_to = [0] * graph_edges
    
    for i in range(graph_edges):
        graph_from[i], graph_to[i] = map(int, input().split())
    
    ids = list(map(int, input().rstrip().split()))
    
    val = int(input())
    
    ans = findShortest(graph_nodes, graph_from, graph_to, ids, val)
    
    fptr.write(str(ans) + '\n')
    
    fptr.close()