from typing import List, Tuple
from queue import Queue
# define a tuple to represent a node in the forest
Node = Tuple[int, int]
# function to perform BFS from a given node and mark all visited nodes
def bfs(forest: List[List[int]], start: Node, visited: List[List[bool]]) -> None:
# create a queue for BFS
q = Queue()
q.put(start)
visited[start[0]][start[1]] = True
# BFS loop
while not q.empty():
curr = q.get()
# add unvisited neighboring nodes to the queue
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
for i in range(4):
nx = curr[0] + dx[i]
ny = curr[1] + dy[i]
if 0 <= nx < len(forest) and 0 <= ny < len(forest[0]) and forest[nx][ny] == 1 and not visited[nx][ny]:
q.put((nx, ny))
visited[nx][ny] = True
# function to count the number of trees in a forest using BFS
def count_trees_in_forest(forest: List[List[int]]) -> int:
count = 0
n, m = len(forest), len(forest[0])
# create a 2D boolean array to keep track of visited nodes
visited = [[False for _ in range(m)] for _ in range(n)]
# iterate over all nodes in the forest and perform BFS from each unvisited tree
for i in range(n):
for j in range(m):
if forest[i][j] == 1 and not visited[i][j]:
bfs(forest, (i, j), visited)
count += 1
return count
# example usage
forest = [
[0, 1, 1, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1],
[0, 0, 0, 0, 0]
]
num_trees = count_trees_in_forest(forest)
print(f"The forest has {num_trees} trees.")