ACM-week4-搜索

迷宫(dfs)

#include<bits/stdc++.h>

using namespace std;

int mp[10][10];//我们的地图

bool vis[10][10]={false};//标记先清零

int a[5]={0,0,1,-1};

int b[5]={-1,1,0,0};//定义我们的方向

int sum,fx,fy,sx,sy,t,n,m,bx,by;

void dfs(int x,int y)

{

   if(x==fx && y==fy)//走到重点

    {

        sum++;//总数加一

        return;

    }

    int next_x,next_y;

    for (int i=0;i<4;i++)

    {

      next_x=x+a[i];

      next_y=y+b[i];//走一步

       if (next_x>=1 && next_x<=n && next_y<=m && next_y>=1 && vis[next_x][next_y]==false && mp[next_x][next_y]==0)//判断不超出边界并没有走过

       {

        vis[next_x][next_y]=true;//走过标记

        dfs(next_x,next_y);//继续搜下一步

        vis[next_x][next_y]=false;//还原状态

       }

    }

}

int main()

{

   cin>>n>>m>>t;

   cin>>sx>>sy>>fx>>fy;

   mp[sx][sy]=1;

   for (int j=1;j<=t;j++)

   {

      cin>>bx>>by;

     mp[bx][by]=1;//地图初始化

   } 

   dfs(sx,sy);//搜一下

   cout<<sum;//输出总数

   return 0;

}

马的遍历(bfs)

#include<bits/stdc++.h>

using namespace std;

int sx[10]={-2,-1,1,2,2,1,-1,-2};

int sy[10]={1,2,2,1,-1,-2,-2,-1};//画个图看看马可以走的八个方向

queue <pair<int,int> > q;//定义一个队列

int mp[405][405];

int vis[405][405];//看有没有走过

int n,m,x,y;

int main()

{

   cin>>n>>m>>x>>y;

   for(int i=1;i<=n;i++)

   {

      for(int j=1;j<=m;j++)

      {

         mp[i][j]=-1;//先初始化,题目说走不到就是-1

      }

    }

   q.push(make_pair(x,y));//加入队列

   vis[x][y]=true;

   mp[x][y]=false;

   while(!q.empty())

    {

        int x = q.front().first;//第一个

        int y = q.front().second;//第二个

        q.pop();//删第一个

        int next_x,next_y;

        for(int i = 0;i<8;i++)

        {

            next_x = x+sx[i];

            next_y = y+sy[i];//走一步

            if(next_x>=1 && next_x<=n && next_y>=1 && next_y<=m && vis[next_x][next_y]==0) //不越界,且没走过

            {

                q.push(make_pair(next_x,next_y));//下一个入队

                vis[next_x][next_y]=true;

                mp[next_x][next_y] = mp[x][y]+1;//步数加一

         }

        }

    }

    for(int i=1;i<=n;i++)

   {

      for(int j=1;j<=m;j++)

      {

         printf("%-5d",mp[i][j]);//输出要注意场宽,看了题解的大佬提醒才写出来

      }

      cout<<endl;

    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值