MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / run_maze

Function run_maze

backtracking/rat_in_maze.py:139–191  ·  view source on GitHub ↗

This method is recursive starting from (i, j) and going in one of four directions: up, down, left, right. If a path is found to destination it returns True otherwise it returns False. Parameters maze: A two dimensional matrix of zeros and ones. i, j : coordinates of

(
    maze: list[list[int]],
    i: int,
    j: int,
    destination_row: int,
    destination_column: int,
    solutions: list[list[int]],
)

Source from the content-addressed store, hash-verified

137
138
139def run_maze(
140 maze: list[list[int]],
141 i: int,
142 j: int,
143 destination_row: int,
144 destination_column: int,
145 solutions: list[list[int]],
146) -> bool:
147 """
148 This method is recursive starting from (i, j) and going in one of four directions:
149 up, down, left, right.
150 If a path is found to destination it returns True otherwise it returns False.
151 Parameters
152 maze: A two dimensional matrix of zeros and ones.
153 i, j : coordinates of matrix
154 solutions: A two dimensional matrix of solutions.
155 Returns:
156 Boolean if path is found True, Otherwise False.
157 """
158 size = len(maze)
159 # Final check point.
160 if i == destination_row and j == destination_column and maze[i][j] == 0:
161 solutions[i][j] = 0
162 return True
163
164 lower_flag = (not i < 0) and (not j < 0) # Check lower bounds
165 upper_flag = (i < size) and (j < size) # Check upper bounds
166
167 if lower_flag and upper_flag:
168 # check for already visited and block points.
169 block_flag = (solutions[i][j]) and (not maze[i][j])
170 if block_flag:
171 # check visited
172 solutions[i][j] = 0
173
174 # check for directions
175 if (
176 run_maze(maze, i + 1, j, destination_row, destination_column, solutions)
177 or run_maze(
178 maze, i, j + 1, destination_row, destination_column, solutions
179 )
180 or run_maze(
181 maze, i - 1, j, destination_row, destination_column, solutions
182 )
183 or run_maze(
184 maze, i, j - 1, destination_row, destination_column, solutions
185 )
186 ):
187 return True
188
189 solutions[i][j] = 1
190 return False
191 return False
192
193
194if __name__ == "__main__":

Callers 1

solve_mazeFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected