File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ """
2
+ Depth-first Search on a 2D grid
3
+
4
+ Note: 'steps' indicates order of expansion, not distance from the source cell.
5
+
6
+ Jessica Yung
7
+ Jan 2018
8
+ """
9
+ import numpy as np
10
+ from queue import Queue
11
+ from grid2d import Grid2D
12
+
13
+ class DFS2D (Grid2D ):
14
+
15
+ def __init__ (self , grid_width , grid_height , visited = None ):
16
+ Grid2D .__init__ (self , grid_width , grid_height , visited )
17
+
18
+ def dfs (self , x , y , steps = 0 ):
19
+ """Depth-First Search algorithm that visits every cell in a 2D grid.
20
+ """
21
+ if x >= self .grid_width or y >= self .grid_height :
22
+ return
23
+ if x < 0 or y < 0 :
24
+ return
25
+ if self .visited [y ][x ]:
26
+ return
27
+
28
+ # Mark current cell as visited
29
+ self .visited [y ][x ] = True
30
+ self .steps_taken [y ][x ] = steps
31
+ steps += 1
32
+
33
+ # Visit every neighbouring cell
34
+ for cell in self .neighbour (x , y ):
35
+ cellx = cell [0 ]
36
+ celly = cell [1 ]
37
+ self .dfs (cellx , celly , steps )
38
+
39
+ dfs = DFS2D (4 , 3 )
40
+ dfs .dfs (1 ,2 )
41
+ print ("Order of expansion: \n " , dfs .steps_taken )
42
+
You can’t perform that action at this time.
0 commit comments