DFS- SDUT1269 走迷宫

4 篇文章 0 订阅

走迷宫

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic
Problem Description

有一个m*n格的迷宫(表示有m行、n列),其中有可走的也有不可走的,如果用1表示可以走,0表示不可以走,输入这m*n个数据和起始点、结束点(起始点和结束点都是用两个数据来描述的,分别表示这个点的行号和列号)。现在要你编程找出所有可行的道路,要求所走的路中没有重复的点,走时只能是上下左右四个方向。如果一条路都不可行,则输出相应信息(用-1表示无路)。
Input

第一行是两个数m,n(1< m, n< 15),接下来是m行n列由1和0组成的数据,最后两行是起始点和结束点。
Output

所有可行的路径,输出时按照左上右下的顺序。描述一个点时用(x,y)的形式,除开始点外,其他的都要用“->”表示。如果没有一条可行的路则输出-1。
Example Input

5 4
1 1 0 0
1 1 1 1
0 1 1 0
1 1 0 1
1 1 1 1
1 1
5 4
1
2
3
4
5
6
7
8
5 4
1 1 0 0
1 1 1 1
0 1 1 0
1 1 0 1
1 1 1 1
1 1
5 4
Example Output

(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(1,2)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(2,3)->(3,3)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(4,1)->(5,1)->(5,2)->(5,3)->(5,4)
(1,1)->(2,1)->(2,2)->(3,2)->(4,2)->(5,2)->(5,3)->(5,4)

DFS的思路,需要记录轨迹

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int m,n,step,flag;
int x1,y1,x_end,y_end;
int s[15][15],book[15][15];
int p[150],q[150];
int nextnum[4][2]={
                    {0,-1},//左
                    {-1,0},//上
                    {0,1},//右
                    {1,0}//下
                };
int judge_out(int x,int y)
{
    if(x>m||x<1||y>n||y<1)
        return 1;
    return 0;
}
void dfs(int x,int y)
{
    if(x==x_end&&y==y_end)
    {
        flag=1;
        for(int i=0;i<step;i++)
        {
            if(i==0)
                printf("(%d,%d)",p[i],q[i]);
            else
            {
                printf("->(%d,%d)",p[i],q[i]);
            }
        }
        printf("\n");
        return ;
    }
    int i;
    for(i=0;i<4;i++)
    {
        int tx=x+nextnum[i][0];
        int ty=y+nextnum[i][1];
        if(judge_out(tx,ty)==0&&book[tx][ty]==0&&s[tx][ty]==1)
        {
            p[step]=tx;
            q[step++]=ty;
            book[tx][ty]=1;
            dfs(tx,ty);
            book[tx][ty]=0;
            step--;
        }
    }
}
int main(int argc, char const *argv[])
{
    int x;
    cin>>m>>n;
    for(int i=1;i<=m;i++)
    {
        for(int j=1;j<=n;j++)
        {
            cin>>s[i][j];
        }
    }
    step=0,flag=0;
    cin>>x1>>y1>>x_end>>y_end;
    book[x1][y1]=1;
    p[0]=x1;
    q[0]=y1;
    step++;
    dfs(x1,y1);
    if(flag==0)
        cout<<"-1"<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值