Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 9619337

Browse filesBrowse files
committed
Adding Shortest Path in Unweighted Cyclic Graph
1 parent 3daadf5 commit 9619337
Copy full SHA for 9619337

File tree

3 files changed

+108
-0
lines changed
Filter options

3 files changed

+108
-0
lines changed

‎README.md

Copy file name to clipboardExpand all lines: README.md
+1Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,7 @@ Solutions to various challenges published at https://coderbyte.com
463463
Solutions to various challenges published at www.hackerrank.com
464464

465465
* Binary Search Tree LCA
466+
* Shortest Path in Unweighted Graph with cycles
466467

467468

468469
## Contributing
+90Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
from typing import Union
2+
3+
4+
class SPUnweightedCyclicGraph:
5+
"""
6+
Have the function f(strArr) take strArr which will be an array of strings which
7+
models a non-looping Graph.The structure of the array will be as follows:
8+
The first element in the array will be the number of nodes N (points) in the
9+
array as a string. The next N elements will be the nodes which can be anything
10+
(A, B, C .. Brick Street, Main Street .. etc.). Then after the Nth element,
11+
the rest of the elements in the array will be the connections between all of the nodes.
12+
They will look like this: (A-B, B-C .. Brick Street-Main Street .. etc.).
13+
Although, there may exist no connections at all.
14+
15+
Input example: ["4", "A", "B", "C", "D", "A-B", "B-D", "B-C", "C-D"]
16+
Expected output: 'A-B-D'
17+
"""
18+
19+
def __call__(self, str_arr: str) -> Union[str, int]:
20+
nodes_count = int(str_arr[0])
21+
nodes = str_arr[1:nodes_count + 1]
22+
connections = [x.split('-') for x in str_arr[nodes_count + 1:]]
23+
24+
_from = nodes[0]
25+
_to = nodes[len(nodes) - 1]
26+
_adj = self._make_adj_list(connections)
27+
28+
traversal = Bfs(_adj, _from)
29+
path = traversal.path_to(_to)
30+
31+
if not path:
32+
return -1
33+
return '-'.join(path)
34+
35+
# Construct adjacency list, so it could be
36+
# consumed by DFS algorithm
37+
@staticmethod
38+
def _make_adj_list(connections):
39+
adj_list = {}
40+
for pair in connections:
41+
# assign an empty list if not exist yet
42+
for x in pair:
43+
if not adj_list.get(x, False):
44+
adj_list[x] = []
45+
adj_list[pair[0]].append(pair[1])
46+
adj_list[pair[1]].append(pair[0])
47+
return adj_list
48+
49+
50+
class Bfs:
51+
def __init__(self, adj, s):
52+
self.marked = {}
53+
self.dist_To = {}
54+
self.edge_to = {}
55+
self._bfs(adj, s)
56+
57+
def path_to(self, v):
58+
if not self.marked.get(v, False):
59+
return False
60+
q = []
61+
x = v
62+
q.append(v)
63+
while not self.dist_To.get(x) == 0:
64+
x = self.edge_to[x]
65+
q.append(x)
66+
q.reverse()
67+
return q
68+
69+
# Simple BFS algorithm, it is shortest way to find shortest path
70+
# on unweighted graph
71+
def _bfs(self, adj, s):
72+
q = []
73+
for v in adj.keys():
74+
self.dist_To[v] = float('infinity')
75+
self.dist_To[s] = 0
76+
self.marked[s] = True
77+
q.append(s)
78+
79+
while not len(q) == 0:
80+
v = q.pop(0)
81+
for w in adj.get(v, []):
82+
if not self.marked.get(w, False):
83+
self.edge_to[w] = v
84+
self.dist_To[w] = self.dist_To[v] + 1
85+
self.marked[w] = True
86+
q.append(w)
87+
88+
def __repr__(self):
89+
return "#<{} edge_to={} dist_To={}>".format(
90+
self.__class__.__name__, self.edge_to, self.dist_To)
+17Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from py_algorithms.challenges.coderbyte.sp_in_unweigted_graph import SPUnweightedCyclicGraph
2+
3+
4+
class TestBinarySearchTreeLca:
5+
def test_impl(self):
6+
inputs = {
7+
'A-B-D': ["4", "A", "B", "C", "D", "A-B", "B-D", "B-C", "C-D"],
8+
'A-E-D-F-G': ["7", "A", "B", "C", "D", "E", "F", "G", "A-B",
9+
"A-E", "B-C", "C-D", "D-F", "E-D", "F-G"],
10+
'c-s-h-d-m': ["5", "c", "h", "d", "s", "m", "c-s", "s-h", "d-m", "h-d"],
11+
'N1-N2-N5': ["5", "N1", "N2", "N3", "N4", "N5", "N1-N3",
12+
"N3-N4", "N4-N5", "N5-N2", "N2-N1"]
13+
}
14+
15+
f = SPUnweightedCyclicGraph()
16+
for key in inputs:
17+
assert f(inputs[key]) == key

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.