1. Problem Description
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.
給出一個m*n的矩陣,每個矩陣裏有一個值,求從左上角走到右下角經過和最小的路徑,輸出最小和。
Note:你只可以走右邊或者下邊。
2. My solution1 BFS(TLE)
先用BFS寫的,每次走到一個節點都要把其鄰近節點掃一下,複雜度是節點數*2,也就是O[n*m*2]。
結果TLE了……
class Solution
{
private :
int dir[2][2];
int row;
int col;
public:
typedef struct
{
int i;
int j;
int val;
} Node;
bool judge(Node tmp)
{
if(tmp.i>=0&&tmp.i<row&&tmp.j>=0&&tmp.j<col)
return true;
else
return false;
}
int BFS(vector<vector<int> >& grid)
{
queue<Node>que;
Node q0= {0,0,grid[0][0]};
que.push(q0);
int ans=(1<<30)-1;
while(!que.empty())
{
Node ff=que.front();
que.pop();
if(ff.i==row-1&&ff.j==col-1)
{
if(ff.val<ans)
ans=ff.val;
continue;
}
for(int i=0; i<2; i++)
{
Node tmp;
int _x=dir[i][0];
int _y=dir[i][1];
tmp.i=ff.i+_x;
tmp.j=ff.j+_y;
if(judge(tmp))
{
tmp.val=ff.val+grid[tmp.i][tmp.j];
que.push(tmp);
}
}
}
return ans;
}
int minPathSum(vector<vector<int> >& grid)
{
dir[0][0]= 1,dir[0][1]= 0;
dir[1][0]= 0,dir[1][1]= 1;
row=grid.size();
if(row==0)
return 0;
col=grid[0].size();
return BFS(grid);
}
};
3. My solution2 Dp(AC)
果然還是要DP啊,這個題的DP很好搞,就是dp[i][j]=min(dp[i-1][j],dp[i][j-1]);
因爲只能向下或者向右走,O[m*n]的複雜度。
class Solution
{
private:
int dir[2][2];
int row;
int col;
vector<vector<int> >dp;
public:
bool judge(int i,int j)
{
if(i>=0&&i<row&&j>=0&&j<col)
return true;
else
return false;
}
int DynamicProgramming(vector<vector<int> >& grid)
{
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
if(judge(i-1,j)&&judge(i,j-1))
dp[i][j]=min(dp[i-1][j],dp[i][j-1]);
else
{
if(judge(i-1,j))
dp[i][j]=dp[i-1][j];
else if(judge(i,j-1))
dp[i][j]=dp[i][j-1];
}
dp[i][j]+=grid[i][j];
}
}
return dp[row-1][col-1];
}
int minPathSum(vector<vector<int> >& grid)
{
row=grid.size();
if(row==0)
return 0;
col=grid[0].size();
for(int i=0; i<row; i++)
{
vector<int>tmp;
dp.push_back(tmp);
for(int j=0; j<col; j++)
{
dp[i].push_back(0);
}
}
return DynamicProgramming(grid);
}
};