LeetCode 797. All Paths From Source to Target
08 Aug 2018Description:
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.
The graph is given as follows: the nodes are 0, 1, …, graph.length – 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
Note:
- The number of nodes in the graph will be in the range [2, 15].
- You can print different paths in any order, but you should keep the order of nodes inside one path.
Example:
input:
[[1,2], [3], [3], []]
output:
[[0,1,3],[0,2,3]]
explanation:
The graph looks like this:
0--->1 | | v v 2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Solution:
class Path:
last = None
node = -1
def __init__(self, last, node):
self.last = last
self.node = node
class Solution(object):
def allPathsSourceTarget(self, graph):
"""
:type graph: List[List[int]]
:rtype: List[List[int]]
"""
start = 0
end = len(graph) - 1
# bfs
queue = []
queue.append(Path(None, start))
endNode = []
while len(queue) > 0:
front = queue.pop(0)
assert front.node != -1
if front.node == end:
endNode.append(front)
else:
for nextNode in graph[front.node]:
queue.append(Path(front, nextNode))
result = []
for node in endNode:
path = []
obj = node
while obj is not None:
path.append(obj.node)
obj = obj.last
path.reverse()
result.append(path)
return result
Simple bredth first search algorithm.