forked from BigEggStudy/LeetCode-CS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0529-Minesweeper.cs
More file actions
65 lines (52 loc) · 1.99 KB
/
0529-Minesweeper.cs
File metadata and controls
65 lines (52 loc) · 1.99 KB
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
57
58
59
60
61
62
63
64
65
//-----------------------------------------------------------------------------
// Runtime: 380ms
// Memory Usage: 35.5 MB
// Link: https://leetcode.com/submissions/detail/373295514/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0529_Minesweeper
{
private static readonly (int dr, int dc)[] directions = { (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1) };
public char[][] UpdateBoard(char[][] board, int[] click)
{
if (board[click[0]][click[1]] == 'M')
{
board[click[0]][click[1]] = 'X';
return board;
}
int N = board.Length;
int M = board[0].Length;
var visisted = new HashSet<(int r, int c)>();
var queue = new Queue<(int r, int c)>();
queue.Enqueue((click[0], click[1]));
var adjList = new List<(int r, int c)>();
while (queue.Count > 0)
{
(int r, int c) = queue.Dequeue();
if (visisted.Contains((r, c))) continue;
visisted.Add((r, c));
board[r][c] = 'B';
adjList.Clear();
var count = 0;
foreach (var dir in directions)
{
var newR = r + dir.dr;
var newC = c + dir.dc;
if (newR < 0 || newR >= N || newC < 0 || newC >= M) continue;
if (board[newR][newC] == 'E')
adjList.Add((newR, newC));
if (board[newR][newC] == 'M')
count++;
}
if (count == 0)
foreach ((int newR, int newC) in adjList)
queue.Enqueue((newR, newC));
else
board[r][c] = (char)('0' + count);
}
return board;
}
}
}