Sicily 1158 Pick numbers

廣搜找權值最小的路徑

#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;
}                         


發佈了144 篇原創文章 · 獲贊 7 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章