def __dfs(graph, start, goal, visited): stack = [start] parents = {start: -1} while len(stack) > 0: v = stack.pop() visited.append(v) if v == goal: break col = graph[v] for i, val in enumerate(col): if val == 1 and i not in visited: stack.append(i) parents.update({i: v}) return get_path(parents, goal, start)
def __bfs(graph, start, goal, visited): q = deque([start]) visited.append(start) parents = {start: -1} while len(q) > 0: if goal in visited: break v = q.popleft() for i, val in enumerate(graph[v]): if val == 1 and i not in visited: q.append(i) visited.append(i) parents.update({i: v}) if i == goal: break return get_path(parents, goal, start)
def dfs(graph, start, goal, visited): if start not in graph.keys() or goal not in graph.keys(): return None stack = [start] parents = {start: 0} while len(stack) > 0: v = stack.pop() visited.append(v) if v == goal: break adjacent = list(graph[v]) for a in adjacent: if a not in visited: stack.append(a) parents.update({a: v}) return get_path(parents, goal, start)
def bfs(graph, start, goal, visited): q = deque([start]) visited.append(start) parents = {start: 0} while len(q) > 0: if goal in visited: break v = q.popleft() adjacent = [c for c in graph[v] if c not in visited] for c in adjacent: q.append(c) visited.append(c) parents.update({c: v}) if c == goal: break return get_path(parents, goal, start)
def __ucs(graph, start, goal, visited): q = PriorityQueue() q.put((0, start)) parents = {start: 0} cumulative_cost = {start: 0} while not q.empty(): if goal in visited: break [vcost, v] = q.get() if v in visited: continue visited.append(v) if v == goal: break for i, ccost in enumerate(graph[v]): if ccost > 0 and i not in visited: ccost += vcost if i in cumulative_cost.keys() and ccost >= cumulative_cost[i]: continue q.put((ccost, i)) parents.update({i: v}) cumulative_cost.update({i: ccost}) return get_path(parents, goal, start)
def ucs(graph, start, goal, visited): q = PriorityQueue() q.put((0, start)) parents = {start: 0} cumulative_cost = {start: 0} while q: if goal in visited: break [vcost, v] = q.get() if v in visited: continue visited.append(v) if v == goal: break adjacent = [(c, graph[v][c]) for c in graph[v].keys() if c not in visited] for (c, ccost) in adjacent: ccost += vcost if c in cumulative_cost.keys() and ccost >= cumulative_cost[c]: continue q.put((ccost, c)) parents.update({c: v}) cumulative_cost.update({c: ccost}) return get_path(parents, goal, start)