-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0286-walls-and-gates.cs
56 lines (45 loc) · 1.31 KB
/
0286-walls-and-gates.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class Solution
{
private Queue<(int, int)> queue = new Queue<(int, int)>();
private int rows;
private int cols;
public void WallsAndGates(int[][] rooms)
{
rows = rooms.Length;
cols = rooms[0].Length;
var visited = new int[rows, cols];
void addRoom(int row, int col)
{
if (row < 0 || col < 0 || row == rows || col == cols || rooms[row][col] == -1 || visited[row, col] == 1)
return;
visited[row, col] = 1;
queue.Enqueue((row, col));
}
for (var i = 0; i < rows; i++)
{
for (var j = 0; j < cols; j++)
{
if (rooms[i][j] == 0)
{
queue.Enqueue((i, j));
visited[i, j] = 1;
}
}
}
var currentDistance = 0;
while (queue.Count > 0)
{
var count = queue.Count;
for (var i = 0; i < count; i++)
{
var (row, col) = queue.Dequeue();
rooms[row][col] = currentDistance;
addRoom(row + 1, col);
addRoom(row - 1, col);
addRoom(row, col + 1);
addRoom(row, col - 1);
}
currentDistance++;
}
}
}