首页 > 代码库 > LeetCode--Minimum Path Sum
LeetCode--Minimum Path Sum
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
struct data { int i; int j; int val; friend bool operator<(data& d1, data& d2) { return d1.val < d2.val; } }; class minpq { public: minpq(int n,int m) { pq = new data[m*n]; size = 0; this->n = n*m; } ~minpq() { delete[] pq; } bool is_empty() const {return size==0;} data del_min() { data res = pq[0]; swap(0,size-1); size--; sink(0,size-1); return res; } void insert(int i, int j, int val) { pq[size].i = i; pq[size].j = j; pq[size].val = val; size++; swim(size-1); } void sink(int loc, int end) { while(loc<end) { int k=2*loc+1; if(k>end) return; if(k<end && pq[k+1]<pq[k]) k++; if(pq[loc] < pq[k]) return ; swap(loc,k); loc = k; } } void swim(int loc) { while(loc >0) { int k = (loc-1)/2; if(pq[k]<pq[loc]) return; swap(loc,k); loc = k; } } private: data* pq; int size; int n; void swap(int i, int j) { data temp = pq[i]; pq[i] = pq[j]; pq[j] = temp; } }; class Solution { public: int minPathSum(vector<vector<int> > &grid) { int n = grid.size(); if(n == 0) return 0; int m = grid[0].size(); vector<vector<int>> res; vector<vector<bool>> flag; for(int i=0; i<n; i++) { vector<int> temp(m,-1); vector<bool> f(m,false); res.push_back(temp); flag.push_back(f); } minpq q(n,m); q.insert(0,0,grid[0][0]); while(!q.is_empty()) { data temp = q.del_min(); int i=temp.i; int j=temp.j; int val = temp.val; res[i][j] = val; if(flag[i][j] == false) { flag[i][j] = true; if(i == (n-1) && j == (m-1)) return val; if(i+1<n) q.insert(i+1,j,grid[i+1][j]+val); if(j+1<m) q.insert(i,j+1,grid[i][j+1]+val); } } return res[n-1][m-1]; } };
LeetCode--Minimum Path Sum
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。