CShap 网格的最大不重复路径数 源代码
时间: 2024-05-31 20:08:17 浏览: 96
以下是C#实现网格的最大不重复路径数的源代码:
using System;
public class GridPaths
{
public static int MaxPaths(int[,] grid)
{
int n = grid.GetLength(0);
int m = grid.GetLength(1);
// Create a 2D array to store the number of unique paths to each cell
int[,] dp = new int[n, m];
// Initialize the number of unique paths to the first cell to 1
dp[0, 0] = 1;
// Fill in the first row and first column
for (int i = 1; i < n; i++)
{
if (grid[i, 0] == 1) break; // If the cell is blocked, stop
dp[i, 0] = 1;
}
for (int j = 1; j < m; j++)
{
if (grid[0, j] == 1) break; // If the cell is blocked, stop
dp[0, j] = 1;
}
// Fill in the rest of the table
for (int i = 1; i < n; i++)
{
for (int j = 1; j < m; j++)
{
if (grid[i, j] == 1) continue; // If the cell is blocked, skip it
// The number of unique paths to cell (i, j) is the sum of the number of unique paths to the cells above and to the left of it
dp[i, j] = dp[i - 1, j] + dp[i, j - 1];
}
}
// The final answer is the number of unique paths to the bottom-right cell
return dp[n - 1, m - 1];
}
public static void Main()
{
int[,] grid = new int[,] {
{0,0,0},
{0,1,0},
{0,0,0}
};
Console.WriteLine(MaxPaths(grid)); // Output: 2
}
}
阅读全文