版权声明:转载请联系博主 https://blog.csdn.net/zxtalentwolf/article/details/84063441
优先队列图搜索方法,超时,查看discussion发现是因为动态规划比这个快。。 = =可能因为优先队列是一棵红黑树要插入的缘故吧。
下面是优先队列的方法。
const int x=[]{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return 0;
}();//这里有个链表记录它的前驱节点
struct POS{
int x;
int y;
int cost;
POS(int a, int b, int c){
x = a;
y = b;
cost = c;
}
friend bool operator < (POS A,POS B) {
return A.cost > B.cost;
}
};
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
priority_queue<POS> q;
int m=grid.size();
int n=grid[0].size();
POS s(0, 0, grid[0][0]);
q.push(s);
while(!q.empty()){
POS t = q.top();
q.pop();
if(t.x == m-1 && t.y == n-1) return t.cost;
if(t.x+1 < m){
POS a(t.x+1,t.y,t.cost+grid[t.x+1][t.y]);
q.push(a);
}
if(t.y+1 < n){
POS a(t.x,t.y+1,t.cost+grid[t.x][t.y+1]);
q.push(a);
}
}
return 0;
}
};
下面是动态规划的方式
const int x=[]{
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return 0;
}();//这里有个链表记录它的前驱节点
const int inf=0x3f3f3f;
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int m=grid.size();
int n=grid[0].size();
int *cost = new int[m*n];
for(int i = 0; i < m*n; i++) cost[i]=inf;
for(int i = 0; i < m ; i++){
for(int j = 0; j < n; j++){
if(i == 0 && j == 0) cost[i * n + j] = grid[i][j];
if(j > 0){
cost[i * n + j] = cost[i * n + j] < cost[i * n + j - 1] + grid[i][j]?cost[i * n + j] : cost[i * n + j - 1] + grid[i][j];
}
if(i > 0){
cost[i * n + j] = cost[i * n + j] < cost[(i-1) * n + j] + grid[i][j]?cost[i * n + j] : cost[(i-1) * n + j] + grid[i][j];
}
}
}
int ans=cost[m*n-1];
delete cost;
return ans ;
}
};