我正在解决一些 leetcode 问题。但是对于这个难题,我不知道如何进一步加快我的算法速度。
https://leetcode.com/problems/minimum-obstacle-removal-to-reach-corner/submissions/1621824895
public class Solution {
public int MinimumObstacles(int[][] grid) {
int m = grid.Length;
int n = grid[0].Length;
var field = new MyDict(m, n, grid);
field[(0,0)].wallsToHere = 0;
List<Cell> toDo = [field[(0,0)]];
while(!toDo.Contains(field[(m-1,n-1)])){
var c = toDo.OrderBy(x=>x.wallsToHere).First();
try{
var testC = field[(c.m-1,c.n)];
CheckCell(testC, c, toDo);
}catch{}
try{
var testC = field[(c.m+1,c.n)];
CheckCell(testC, c, toDo);
}catch{}
try{
var testC = field[(c.m,c.n-1)];
CheckCell(testC, c, toDo);
}catch{}
try{
var testC = field[(c.m,c.n+1)];
CheckCell(testC, c, toDo);
}catch{}
toDo.Remove(c);
c.done = true;
}
return field[(m-1,n-1)].wallsToHere;
}
private void CheckCell(Cell testC, Cell c, List<Cell> toDo){
if(!toDo.Contains(testC) && !testC.done){
if (testC.wallsToHere > c.wallsToHere + testC.value){
testC.wallsToHere = c.wallsToHere + testC.value;
}
toDo.Add(testC);
}
}
}
public class Cell(int value, int m, int n){
public int value = value;
public int wallsToHere = (int)Math.Pow(10,5)+1;
public int m = m;
public int n = n;
public bool done = false;
}
public class MyDict:Dictionary<(int,int),Cell>
{
public MyDict(int m, int n, int[][] grid){
this.m=m;
this.n=n;
this._grid = grid;
}
private int m;
private int n;
private int[][] _grid;
public new Cell this[(int,int) key]{
get{
if (base.Keys.Contains(key)){
return base[key];
}
else if (key.Item1 < 0 || key.Item2 < 0 || key.Item1 > m || key.Item2 > n){
throw new Exception();
}
else{
Cell c = new Cell(_grid[key.Item1][key.Item2], key.Item1, key.Item2);
base[key] = c;
return c;
}
}
}
}
除了我的 MyDict 实现之外,我不确定如何使用我的 Dijkstra 方法更快地解决这个问题。
如果可能的话,我怎样才能加快速度并改进,而不使用其他方法?