首页 > 代码库 > 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