File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #Breadth first search
2+ class queue ():
3+ def __init__ (self ):
4+ self .array = []
5+ def push (self , data ):
6+ self .array .append (data )
7+ def pop (self ):
8+ if not self .array :
9+ return
10+ del self .array [0 ]
11+ def top (self ):
12+ return self .array [0 ]
13+ def isEmpty (self ):
14+ if not self .array :
15+ return True
16+ return False
17+
18+ def bfs (m , q , result , visited ):
19+ #If q is not empty
20+ if not q .isEmpty ():
21+ #Pop the top element
22+ t = q .top ()
23+ q .pop ()
24+ #Add it to result
25+ result .append (t )
26+ #Add all its adjacent unvisited elements to the q
27+ for adjacentElement in range (9 ):
28+ if (m [t ][adjacentElement ] == 1 and visited [adjacentElement ] == 0 ):
29+ #Mark it visited
30+ visited [adjacentElement ] = 1
31+ #Add it to the q
32+ q .push (adjacentElement )
33+ bfs (m , q , result , visited )
34+ return result
35+
36+ def foo (matrix ):
37+ q = queue ()
38+ q .push (0 )
39+ v = [0 for col in range (9 )]
40+ v [0 ] = 1
41+ r = bfs (matrix , q , [], v )
42+ print r
43+
44+ #Main Program
45+ matrix = [[0 for col in range (9 )] for row in range (9 )]
46+ matrix [0 ][1 ] = 1
47+ matrix [0 ][8 ] = 1
48+ matrix [1 ][0 ] = 1
49+ matrix [8 ][0 ] = 1
50+ matrix [8 ][2 ] = 1
51+ matrix [8 ][6 ] = 1
52+ matrix [2 ][3 ] = 1
53+ matrix [2 ][4 ] = 1
54+ matrix [2 ][5 ] = 1
55+ matrix [2 ][8 ] = 1
56+ matrix [3 ][2 ] = 1
57+ matrix [4 ][2 ] = 1
58+ matrix [4 ][7 ] = 1
59+ matrix [5 ][2 ] = 1
60+ matrix [5 ][6 ] = 1
61+ matrix [6 ][8 ] = 1
62+ matrix [6 ][5 ] = 1
63+ matrix [7 ][4 ] = 1
64+ matrix [7 ][6 ] = 1
65+ foo (matrix )
You can’t perform that action at this time.
0 commit comments