Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

DEPTH FIRST SEARCH¶

Strategy: Expand the deepest node first


Implementation: Fringe is a LIFO queue (a stack)

Search is performed by extracting and inserting from the front of the list (LIFO)

DFS progresses by expanding the first child node of the search tree that appears and
thus going deeper and deeper until a goal node is found, or until it hits a node that has
no children. Then the search backtracks, returning to the most recent node it
hasn†™t finished exploring.

Algorithm¶
Depth First Search
Let fringe be a list containing the initial state
Loop
if fringe is empty return failure

Node <-remove-first (fringe)


if Node is a goal
then return the path from initial state to Node
else generate all successors of Node, and

merge the newly generated nodes into fringe


add generated nodes to the front of fringe
End Loop

Start by putting the graph's start node on top of stack

In [1]:
## declare classes of nodes,edges,and stack
In [2]:
class vertex:

def __init__(point, name):


point.out_edges = []
point.name = name
point.is_goal = False

def add_link(point, node):


point.out_edges.append(link(node))

def find_goal(point):
point.is_goal= True

class link:

def __init__(point, node):


point.node = node
def to(point):
return point.node
class Stack:
def __init__(point):
point.items = []
def emp(point):
return point.items == []
def push(point, item):
point.items.append(item)
def pop(point):
return point.items.pop()
In [3]:
# Input Graph structure
In [4]:
A=vertex('A');
B=vertex('B');
C=vertex('C');
D=vertex('D');
E=vertex('E');
F=vertex('F');
G=vertex('G');
A.add_link(B);
A.add_link(C);
A.add_link(D);
B.add_link(E);
C.add_link(F);
C.add_link(G);
F.find_goal();

Main module of DFS¶


In [6]:
def dfs(v):
visited = set()
q = Stack()
q.push((v, [v.name]))
while not q.emp():
[current_node,path]=q.pop();
visited.add(current_node)
if current_node.is_goal:
print(path)
else:
for edge in current_node.out_edges:
child = edge.to()
q.push((child, path + [child.name]))
dfs(A)
['A', 'C', 'F']

You might also like