CH
For all software engineering , AI,Cyber security and computer science students and graduates challenging questions implemented whatever programming languages For answering coding challenges: https://t.me/AnswerForCodingChallenges
Більше- Підписники
- Перегляди допису
- ER - коефіцієнт залучення
Триває завантаження даних...
Триває завантаження даних...
You have given a un directional graph. Your task is to count how many nodes are there in each disconnected component. ed. 1------2 \ 3 has 3 nodes. The given graph is as follows: 13 ==> Number of vertices from 1 to N 12 ===>Number of edges The next edges lines are the nodes connection description. 1 2 1 3 2 4 3 4 5 6 5 8 6 7 8 9 7 9 10 11 10 12 11 12
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
We match you the best practice peers and set your interviews together, including real-world interview questions, high-quality video chat, collaborative environment, and peer feedback.
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
import heapq def calculate_distances(graph, starting_vertex): distances = {vertex: float('infinity') for vertex in graph} distances[starting_vertex] = 0 pq = [(0, starting_vertex)] while len(pq) > 0: current_distance, current_vertex = heapq.heappop(pq) # Nodes can get added to the priority queue multiple times. We only # process a vertex the first time we remove it from the priority queue. if current_distance > distances[current_vertex]: continue for neighbor, weight in graph[current_vertex].items(): distance = current_distance + weight # Only consider this new path if it's better than any path we've # already found. if distance < distances[neighbor]: distances[neighbor] = distance heapq.heappush(pq, (distance, neighbor)) return distances example_graph = { 'U': {'V': 2, 'W': 5, 'X': 1}, 'V': {'U': 2, 'X': 2, 'W': 3}, 'W': {'V': 3, 'U': 5, 'X': 3, 'Y': 1, 'Z': 5}, 'X': {'U': 1, 'V': 2, 'W': 3, 'Y': 1}, 'Y': {'X': 1, 'W': 1, 'Z': 1}, 'Z': {'W': 5, 'Y': 1}, } print(calculate_distances(example_graph, 'X')) # => {'U': 1, 'W': 2, 'V': 2, 'Y': 1, 'X': 0, 'Z': 2}