using
System;
using
System.Collections.Generic;
class
Program {
class
Node {
public
int
x;
public
int
y;
public
Node(
int
x,
int
y)
{
this
.x = x;
this
.y = y;
}
}
static
void
bfs(
int
[][] forest, Node start,
bool
[][] visited)
{
Queue<Node> q =
new
Queue<Node>();
q.Enqueue(start);
visited[start.x][start.y] =
true
;
while
(q.Count != 0) {
Node curr = q.Dequeue();
int
[] dx = { -1, 0, 1, 0 };
int
[] dy = { 0, 1, 0, -1 };
for
(
int
i = 0; i < 4; i++) {
int
nx = curr.x + dx[i];
int
ny = curr.y + dy[i];
if
(nx >= 0 && nx < forest.Length && ny >= 0
&& ny < forest[0].Length
&& forest[nx][ny] == 1
&& !visited[nx][ny]) {
q.Enqueue(
new
Node(nx, ny));
visited[nx][ny] =
true
;
}
}
}
}
static
int
count_trees_in_forest(
int
[][] forest)
{
int
count = 0;
int
n = forest.Length;
int
m = forest[0].Length;
bool
[][] visited =
new
bool
[n][];
for
(
int
i = 0; i < n; i++) {
visited[i] =
new
bool
[m];
}
for
(
int
i = 0; i < n; i++) {
for
(
int
j = 0; j < m; j++) {
if
(forest[i][j] == 1 && !visited[i][j]) {
bfs(forest,
new
Node(i, j), visited);
count++;
}
}
}
return
count;
}
static
void
Main(
string
[] args)
{
int
[][] forest = {
new
int
[] { 0, 1, 1, 0, 0 },
new
int
[] { 0, 0, 0, 0, 0 },
new
int
[] { 0, 0, 0, 0, 0 },
new
int
[] { 0, 0, 0, 0, 1 },
new
int
[] { 0, 0, 0, 0, 0 } };
int
num_trees = count_trees_in_forest(forest);
Console.WriteLine(
"The forest has "
+ num_trees
+
" trees."
);
}
}