Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
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
2 2 0 2 1 0 3 3 0 0 0 0 0 0 0 0 0
Sample Output
1 -1
Problem Source
ZSUACM Team Member
Solution
给出m*n的矩阵,找出一条路从左上到右下,方向只有向右或者向下,求路的最小正权值。
我一开始想到的是dp,状态转移方程:dp(i,j)=min(dp(i-1,j), dp(i, j+1))+data[i][j]。但是要求的是最小正权值,可能存在的情况是虽然最小权值是负的,但是有正权值的答案。
这时候dp的方法就是有漏洞的。
然后就直接穷举所有路了,BFS。
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct Point
{
int x, y, sum;
Point() {}
Point(int i, int j, int k) : x(i), y(j), sum(k) {}
}temp;
int data[15][15];
int main()
{
int i, j, m, n;
while (cin >> m >> n)
{
for (i = 0; i < m; ++i)
for (j = 0; j < n; ++j) cin >> data[i][j];
int ans = 1e9;//预设的答案
queue<Point> q;
q.push(Point(0, 0, data[0][0]));
while (!q.empty())
{
temp = q.front();
q.pop();
if (temp.x == m-1 && temp.y == n-1 && temp.sum > 0)
ans = min(temp.sum, ans);
if (temp.x + 1 < m) q.push(Point(temp.x+1, temp.y, temp.sum+data[temp.x+1][temp.y]));//right
if (temp.y + 1 < n) q.push(Point(temp.x, temp.y+1, temp.sum+data[temp.x][temp.y+1]));//down
}
if (ans != 1e9) cout << ans << endl;
else cout << -1 << endl;
}
return 0;
}