-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution542.cs
52 lines (47 loc) · 1.31 KB
/
Solution542.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
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution542
{
/// <summary>
/// 542. 01 Matrix - Medium
/// <a href="https://leetcode.com/problems/01-matrix">See the problem</a>
/// </summary>
public int[][] UpdateMatrix(int[][] mat)
{
var m = mat.Length;
var n = mat[0].Length;
var queue = new Queue<(int, int)>();
var directions = new[] { (0, 1), (0, -1), (1, 0), (-1, 0) };
for (var i = 0; i < m; i++)
{
for (var j = 0; j < n; j++)
{
if (mat[i][j] == 0)
{
queue.Enqueue((i, j));
}
else
{
mat[i][j] = int.MaxValue;
}
}
}
while (queue.Count > 0)
{
var (i, j) = queue.Dequeue();
foreach (var (di, dj) in directions)
{
var ni = i + di;
var nj = j + dj;
if (ni < 0 || ni >= m || nj < 0 || nj >= n || mat[ni][nj] <= mat[i][j] + 1)
{
continue;
}
mat[ni][nj] = mat[i][j] + 1;
queue.Enqueue((ni, nj));
}
}
return mat;
}
}