校赛 D 小鑫的漂流

题目描述

小鑫有一天突然想去漂流,他来到一个既有小河又有土地的小岛上。他开始时站在岛的北面,还未上岛。现在他想要从岛的北面漂流到岛的南面去,由于有些地方可能被土地拦住,导致他无法直接顺着小河漂流到南面去。但小鑫有特殊的技巧,他可以挖穿土地,这样就可以顺利的漂到南面去了。小鑫又很懒,他想尽可能少的挖土,现在请问,他最少需要挖多少块土才能从岛的北面到南面去。

输入格式

第一行n, m,分别代表小岛的行数和列数
一个n*m的矩阵,0代表这个地方是小河,1代表是土地。
(1<=n,m<=10)
输出

最少要挖多少块土
样例输入

7 7
1 1 1 1 0 1 1
1 1 1 1 0 0 1
1 1 1 1 1 0 1
1 1 0 1 1 0 1
1 1 0 1 1 1 1
1 0 0 1 1 1 1
1 0 1 1 1 1 1

7 7
0 0 0 0 0 0 0
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 0 1 0 1 1
1 0 0 0 0 0 1
0 0 0 0 0 0 0

8 8
1 1 1 1 1 0 1 1
1 0 1 1 1 0 1 1
1 0 1 0 1 0 1 0
1 0 1 1 1 0 1 1
0 0 1 1 0 0 0 0
1 0 1 1 1 1 1 1
1 0 1 1 1 1 1 1
1 1 1 0 1 1 1 1
样例输出

2
3

2

比赛的时候没想到用优先队列TVT。。然后就TLE了。思路并不难

/*AC*/
#include <cstdio>
#include <iostream>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;

#define INF 10000

struct node{
    int x, y, t;
};

int a[12][12];
bool vis[12][12];
int dx[] = {1, 0, -1, 0};
int dy[] = {0, 1, 0, -1};
int m, n;
int mint;

bool operator < (const node i, const node j){ //必须重载 < 运算符
    return i.t > j.t;
}

priority_queue<node> q;

bool check(int x, int y){
    if(x>=0 && x<m && y>=0 && y<n) return true;
    else return false;
}

void bfs(int x, int y){
    memset(vis, 0, sizeof(vis));
    while(!q.empty()) q.pop();
    node f, n;
    f.x = x; f.y = y; f.t = 0;
    if(a[x][y] == 1) f.t++;
    q.push(f);
    while(!q.empty()){
        f = q.top(); q.pop();
        if(f.x == m-1){
            if(f.t < mint) mint = f.t;
        }
        if(f.t > mint) break;
        for(int i=0; i<4; i++){
            n.x = f.x + dx[i];
            n.y = f.y + dy[i];
            if(check(n.x, n.y) && !vis[n.x][n.y]){
                n.t = f.t;
                if(a[n.x][n.y] == 1) n.t++;
                q.push(n);
                vis[n.x][n.y] = true;
            }
        }
    }
}

int main(){
    while(~scanf("%d%d", &m, &n)){
        for(int i=0; i<m; i++)
            for(int j=0; j<n; j++)
            scanf("%d", &a[i][j]);
        mint = INF;
        for(int j=0; j<n; j++)
            bfs(0, j);
        printf("%d\n", mint);
    }
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值