-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy path0980-UniquePathsIII.cs
61 lines (52 loc) · 1.93 KB
/
0980-UniquePathsIII.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
57
58
59
60
61
//-----------------------------------------------------------------------------
// Runtime: 92ms
// Memory Usage: 23.5 MB
// Link: https://leetcode.com/submissions/detail/399389571/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0980_UniquePathsIII
{
private readonly (int dr, int dc)[] direction = new (int dr, int dc)[4] { (1, 0), (-1, 0), (0, 1), (0, -1) };
private int count = 0;
public int UniquePathsIII(int[][] grid)
{
int rows = grid.Length, cols = grid[0].Length;
int nonObstacles = 0, startRow = -1, startCol = -1;
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
{
int cell = grid[row][col];
if (cell >= 0)
nonObstacles += 1;
if (cell == 1)
{
startRow = row;
startCol = col;
}
}
Backtrack(grid, startRow, startCol, nonObstacles);
return this.count;
}
private void Backtrack(int[][] grid, int row, int col, int nonObstacles)
{
if (grid[row][col] == 2 && nonObstacles == 1)
{
this.count++;
return;
}
int rows = grid.Length, cols = grid[0].Length;
int temp = grid[row][col];
grid[row][col] = -2;
nonObstacles -= 1;
foreach ((int dr, int dc) in direction)
{
int newRow = row + dr;
int newCol = col + dc;
if (newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && grid[newRow][newCol] >= 0)
Backtrack(grid, newRow, newCol, nonObstacles);
}
grid[row][col] = temp;
}
}
}