廣搜找權值最小的路徑
#include <stdio.h>
#include <memory.h>
#include <deque>
using namespace std;
int matrix[12][12];
int n,m;
struct Node {
int row, col;
int num;
};
int BFS() {
deque<Node> q;
Node tmp;
Node next;
tmp.row=tmp.col=0;
tmp.num=matrix[0][0];
int result=10000000;
q.push_back(tmp);
while (!q.empty()) {
tmp = q.front();
q.pop_front();
if (tmp.row+1<n) {
next.row = tmp.row+1;
next.col = tmp.col;
next.num = tmp.num+matrix[next.row][next.col];
q.push_back(next);
}
if (tmp.col+1<m) {
next.row=tmp.row;
next.col=tmp.col+1;
next.num=tmp.num+matrix[next.row][next.col];
q.push_back(next);
}
if (tmp.row==n-1&&tmp.col==m-1) {
if (tmp.num>0&&tmp.num<result)
result=tmp.num;
}
}
return result;
}
int main() {
int i,j;
int sum;
while (scanf("%d",&n)!=EOF) {
scanf("%d",&m);
for (i=0;i<n;i++) {
for (j=0;j<m;j++) {
scanf("%d",&matrix[i][j]);
}
}
sum=BFS();
if (sum!=10000000)
printf("%d\n", sum);
else
printf("-1\n");
}
return 0;
}