Description
Given a matrix of size M*N, the elements of which are integer numbers from -10 to 10. You task is to go from the top-left corner (1, 1) to the bottom-right corner (M, N). You can only move right or down, and you can not go out of the matrix. The number in the grid you passed must be picked. The sum of numbers you picked must be positive and as minimal as possible.
Input
The input contains several test cases.
The first line of each test case are two integer numbers M, N (2<=M<=10, 2<=N<=10), indicating the number of rows and columns of the matrix. The following M lines, each contains N integer numbers.
Output
For each test case, output the sum of numbers you picked on a single line. If you can't get a positive sum, output -1.
Sample Input
Copy sample input to clipboard
2 2
0 2
1 0
3 3
0 0 0
0 0 0
0 0 0
Sample Output
1
-1
题目大意:
给一个M*N的格子,现在需要从左上角走到右下角,并且只能往下或往右走,并且要把走过的格子中的数加起来,现在要求和为正并且越小越好,求和。
利用bfs求解最小值。
#include<cstdio>
#include<queue>
using namespace std;
#define MAX 100000
int ans,row,col;
int map[11][11];
int dir[2][2]={1,0,
0,1};
struct node{
int row;
int col;
int sum;
};
void bfs()
{
queue<node> que;
node first;
first.row = 1;
first.col = 1;
first.sum = map[1][1];
que.push(first);
node p,temp;
while(!que.empty())
{
p = que.front();
que.pop();
if(p.row == row&&p.col == col&&p.sum>0)
{
ans = min(p.sum,ans);
}
for(int i = 0;i < 2;i++)
{
temp = p;
temp.row += dir[i][0];
temp.col += dir[i][1];
if(temp.row >=1 && temp.col>=1 && temp.row<=row && temp.col<=col)
{
temp.sum += map[temp.row][temp.col];
que.push(temp);
}
}
}
}
int main()
{
freopen("in.txt","r",stdin);
int i,j;
while(scanf("%d%d",&row,&col)==2)
{
ans = MAX;
for(i=1;i<=row;i++)
for(j=1;j<=col;j++)
scanf("%d",&map[i][j]);
bfs();
if(ans == MAX)
printf("-1\n");
else
printf("%d\n",ans);
}
}
由于数据量较小,我们也可以利用dfs
#include<cstdio>
#include<queue>
using namespace std;
#define MAX 100000
int ans,row,col;
int map[11][11];
int dir[2][2]={1,0,
0,1};
void dfs(int r,int c,int sum)
{
if(r==row && c == col)
{
if(sum > 0 && sum < ans)
{
ans = sum;
}
return;
}
if(r+1>=1 && r+1<=row && c>=1&& c<=col)
{
dfs(r+1,c,sum+map[r+1][c]);
}
if(r>=1 && r<=row && c+1>=1&& c+1<=col)
{
dfs(r,c+1,sum+map[r][c+1]);
}
}
int main()
{
freopen("in.txt","r",stdin);
int i,j;
while(scanf("%d%d",&row,&col)==2)
{
ans = MAX;
for(i=1;i<=row;i++)
for(j=1;j<=col;j++)
scanf("%d",&map[i][j]);
//bfs();
dfs(1,1,map[1][1]);
if(ans == MAX)
printf("-1\n");
else
printf("%d\n",ans);
}
}