mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-04-29 20:26:07 -04:00
Update matrix_dfs_and_bfs.py
This commit is contained in:
parent
0f85ea546c
commit
fde384b038
@ -2,22 +2,12 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
# author: bt3gl
|
# author: bt3gl
|
||||||
|
|
||||||
'''
|
|
||||||
Given an m x n 2D binary grid grid which represents a map of
|
|
||||||
'1's (land) and '0's (water), return the number of islands.
|
|
||||||
An island is surrounded by water and is formed by connecting
|
|
||||||
adjacent lands horizontally or vertically. You may assume all
|
|
||||||
four edges of the grid are all surrounded by water.
|
|
||||||
'''
|
|
||||||
|
|
||||||
def num_island_dfs(grid) -> int:
|
def num_island_dfs(grid) -> int:
|
||||||
|
|
||||||
LAND = '1'
|
LAND = '1'
|
||||||
answer = 0
|
answer = 0
|
||||||
|
|
||||||
#######################
|
|
||||||
### go dfs
|
|
||||||
#######################
|
|
||||||
def dfs(row, col):
|
def dfs(row, col):
|
||||||
|
|
||||||
if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] != LAND:
|
if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] != LAND:
|
||||||
@ -29,16 +19,12 @@ def num_island_dfs(grid) -> int:
|
|||||||
dfs(row, col - 1)
|
dfs(row, col - 1)
|
||||||
dfs(row, col + 1)
|
dfs(row, col + 1)
|
||||||
|
|
||||||
#######################
|
|
||||||
## loop through the board
|
|
||||||
#######################
|
|
||||||
for i in range(len(grid)):
|
for i in range(len(grid)):
|
||||||
for j in range(len(grid[0])):
|
for j in range(len(grid[0])):
|
||||||
if grid[i][j] == LAND:
|
if grid[i][j] == LAND:
|
||||||
answer += 1
|
answer += 1
|
||||||
dfs(i, j)
|
dfs(i, j)
|
||||||
|
|
||||||
|
|
||||||
return answer
|
return answer
|
||||||
|
|
||||||
|
|
||||||
@ -48,9 +34,6 @@ def num_island_bfs(grid) -> int:
|
|||||||
answer = 0
|
answer = 0
|
||||||
queue = collections.deque()
|
queue = collections.deque()
|
||||||
|
|
||||||
#######################
|
|
||||||
### go dfs
|
|
||||||
#######################
|
|
||||||
def bfs(row, col, queue):
|
def bfs(row, col, queue):
|
||||||
|
|
||||||
delta = [(1, 0), (0, 1), (-1, 0), (0, -1)]
|
delta = [(1, 0), (0, 1), (-1, 0), (0, -1)]
|
||||||
@ -67,9 +50,7 @@ def num_island_bfs(grid) -> int:
|
|||||||
grid[px][py] = 'x'
|
grid[px][py] = 'x'
|
||||||
queue.append((px, py))
|
queue.append((px, py))
|
||||||
|
|
||||||
#######################
|
|
||||||
## loop through the board
|
|
||||||
#######################
|
|
||||||
for i in range(len(grid)):
|
for i in range(len(grid)):
|
||||||
for j in range(len(grid[0])):
|
for j in range(len(grid[0])):
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user