this is a homework of mine, I wrote some code but it doesn't work.
s$t
###
###
this is a graph that is given to the script as input, using a matrix.
i convert this matrix to a graph with this format.
[['node_1','node_2'],['node_1,'node_3'] ...]
each item of the list represents two connected nodes.
$ means blocked, # means unblocked.
s means start and t means target/destination.
I've read an article about implementing longest path algorithm and came up with dfs.
here is my code:
from collections import defaultdict
total_lines = input()
rows = []
edges = []
for i in range(int(total_lines)):
rows.append(input())
start = ''
end = ''
for r,row in enumerate(rows):
for c,column in enumerate(row):
if column == "$": continue
this = rows[r][c]
this_id = f"{r}-{c}"
# print(this)
if this == 's':
start = this_id
if this == 't':
end = this_id
if (c<len(row)-1):
next_column = row[c+1]
if next_column == "$":
continue
edges.append([f"{r}-{c}",f"{r}-{c+1}"])
if (r<len(rows)-1):
next_row = rows[r+1]
if next_row[r] == "$":
continue
edges.append([f"{r}-{c}",f"{r+1}-{c}"])
def DFS(G,v,seen=None,path=None):
if seen is None: seen = []
if path is None: path = [v]
seen.append(v)
paths = []
for t in G[v]:
if t not in seen:
t_path = path + [t]
paths.append(tuple(t_path))
paths.extend(DFS(G, t, seen[:], t_path))
return paths
G = defaultdict(list)
for (s,t) in edges:
G[s].append(t)
G[t].append(s)
all_paths = [p for ps in [DFS(G, n) for n in set(G)] for p in ps]
max_len = max(len(p) for p in all_paths)
max_paths = [p for p in all_paths if len(p) == max_len]
for p in max_paths:
if p[0] == start and p[-1] == end:
print(p)