We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Far Vertices
Far Vertices
Sort by
recency
|
23 Discussions
|
Please Login in order to post a comment
Here is my solution in java, javascript, python, C, C++, Csharp HackerRank Far Vertices Problem Solution
Here is Far Vertices problem solution - https://programs.programmingoneonone.com/2021/07/hackerrank-far-vertices-problem-solution.html
PYTHON ACCURATE SOLUTION
import math import os import random import re import sys from collections import Counter
def farVertices(n, k, edges): tree = {} for edge in edges: tree[edge[0],edge[1]] = 1 tree[edge[1],edge[0]] = 1 tree_paths = len(tree) cont_flag = True while cont_flag: for edge in edges: matches = {x:y for x,y in tree.items() if edge[1] == x[0]} for match in matches.keys(): if (edge[0],match[1]) not in tree.keys() and edge[0] != match[1]: tree[edge[0],match[1]] = matches[match] + 1 tree[match[1],edge[0]] = matches[match] + 1 matches = {x:y for x,y in tree.items() if edge[0] == x[1]} for match in matches.keys(): if (edge[1],match[0]) not in tree.keys() and edge[1] != match[0]: tree[edge[1],match[0]] = matches[match] + 1 tree[match[0],edge[1]] = matches[match] + 1 if len(tree) == tree_paths: cont_flag = False tree_paths = len(tree) removed = 0 cont_flag = True while cont_flag: matches = [x[0] for x,y in tree.items() if y>k] if len(matches)==0: cont_flag = False else: removed += 1 match_count = Counter(matches) maxcount = max([y for x,y in match_count.items()]) match_max = [x for x,y in match_count.items() if y==maxcount] remove_node = match_max[0] nodes_to_remove = [x for x in tree.keys() if x[0]==remove_node or x[1]==remove_node] print(nodes_to_remove) for node in nodes_to_remove: del tree[node] return removed
if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')
Python3 solution
Let's re-word this question : You're given a graph as input (in the form of pairs of vertices; every pair represents an edge).
"Your task is to mark as small number of vertices as possible, such that, the maximum distance between two unmarked vertices is less than or equal to K."
The above sentence says you need to mark (assume, mark = delete a vertex) so that the remaining number of vertices have atmost K length between them. In other words : find the minimum number of vertices you need to remove so that the remaining tree has path <= K between the vertices. Hint : Use floyd warshall algorithm.