forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cs
40 lines (39 loc) · 1.38 KB
/
Solution.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
using System;
using System.Collections.Generic;
using System.Linq;
public class Solution {
public int NumIslands(char[][] grid)
{
var queue = new Queue<Tuple<int, int>>();
var lenI = grid.Length;
var lenJ = lenI == 0 ? 0 : grid[0].Length;
var paths = new int[,] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
var result = 0;
for (var i = 0; i < lenI; ++i)
{
for (var j = 0; j < lenJ; ++j)
{
if (grid[i][j] == '1')
{
++result;
grid[i][j] = '0';
queue.Enqueue(Tuple.Create(i, j));
while (queue.Any())
{
var position = queue.Dequeue();
for (var k = 0; k < 4; ++k)
{
var next = Tuple.Create(position.Item1 + paths[k, 0], position.Item2 + paths[k, 1]);
if (next.Item1 >= 0 && next.Item1 < lenI && next.Item2 >= 0 && next.Item2 < lenJ && grid[next.Item1][next.Item2] == '1')
{
grid[next.Item1][next.Item2] = '0';
queue.Enqueue(next);
}
}
}
}
}
}
return result;
}
}