洛谷p1605迷宫 dfs

emmmmm~

这道题是一道模板深搜吧

题目背景

迷宫 【问题描述】

给定一个N*M方格的迷宫,迷宫里有T处障碍,障碍处不可通过。给定起点坐标和

终点坐标,问: 每个方格最多经过1次,有多少种从起点坐标到终点坐标的方案。在迷宫

中移动有上下左右四种方式,每次只能移动一个方格。数据保证起点上没有障碍。

输入样例 输出样例

【数据规模】

1≤N,M≤5

题目描述

输入输出格式

输入格式:

 

【输入】

第一行N、M和T,N为行,M为列,T为障碍总数。第二行起点坐标SX,SY,终点

坐标FX,FY。接下来T行,每行为障碍点的坐标。

 

输出格式:

 

【输出】

给定起点坐标和终点坐标,问每个方格最多经过1次,从起点坐标到终点坐标的方

案总数。

 

输入输出样例

输入样例#1:
2 2 1
1 1 2 2
1 2
输出样例#1:
1

 思路:

读入图的大小然后读入起点与终点

然后读入障碍的位置

把障碍的位置标记为1

走过的也标为1

走通后把非障碍的还原成0 

 

#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
const int fx[4] = {-1,1,0,0};     //走的方向
const int fy[4] = {0,0,-1,1};
int  n,m,t,sx,sy,ex,ey;           //行,列,障碍数量,起点,终点
int tx,ty;
int ans = 0;
int vis[6][6];
inline void read(int &x){         //快读
    int f = 1;x = 0;char ch;
    do{ch = getchar();if(ch == '-') f = -1;    }
    while(ch < '0' || ch > '9'); do{
        x = x * 10 + ch - '0';
        ch = getchar();
    } 
    while(ch >= '0' && ch <= '9');x *= f;
}
void dfs(int x,int y){ 
    if(x > n || y >m || x < 1|| y < 1||vis[x][y]) return;  //判断越界与是否走过
    if(x == ex && y == ey) {ans++;return;}          //到终点答案加一并退出
    vis[x][y] = 1;                        //走过的标记为1
    for(int i = 0;i < 4;i++) dfs(x+fx[i],y+fy[i]);     //四个方向dfs
    vis[x][y] = 0;                                            //还原 
}
int main(){
    read(n);read(m);read(t);
    read(sx);read(sy);read(ex);read(ey);
    for(int i = 1;i <= t;i++){
        read(tx);read(ty);
        vis[tx][ty] = 1;                                    //障碍标记 
    }
    dfs(sx,sy); 
    cout<<ans;
    return 0;
} 

 

 

 

  

 

转载于:https://www.cnblogs.com/breast/p/7526983.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值