week4(搜索)

搜索

4-1 迷宫

题目链接

LGP1605

解题思路

思路:
显然的DFS思路。注意每一次搜索后经过的地方需要打标记vis[N],并且本次搜索完后需要重置标记。

参考代码:

#include<bits/stdc++.h>
using namespace std;
int n,m,t;
int sx,sy,fx,fy;
int cnt=0;
int dir1[10]={0,1,0,-1,0};
int dir2[10]={0,0,1,0,-1};
bool b[8][8];
bool vis[8][8];
void doit(int x,int y){
    

    vis[x][y]=1;

    if (x==fx && y==fy){
        cnt++;
        return;
    }

    for (int i=1; i<=4; i++){
        int dirx=x+dir1[i];
        int diry=y+dir2[i];
        if (dirx>=1 && dirx<=n && diry>=1 && diry<=m && !b[dirx][diry] && !vis[dirx][diry]){
            doit(dirx,diry);
            vis[dirx][diry]=0;
        }
    }
}

int main(){
    cin>>n>>m>>t;
    cin>>sx>>sy>>fx>>fy;
    memset(b,0,sizeof(b));
    
    for (int i=1; i<=t; i++){
        int ax,ay;
        cin>>ax>>ay;
        b[ax][ay]=1; 
    }
    doit(sx,sy);
    cout<<cnt;
    system("pause");
    return 0;
}

7-2 马的遍历

题目链接

LGP1443

题目思路

思路:
显然的BFS思路,可以用结构体+queue进行数据处理。其中结构体num记录走到该点的最少步数。注意queuepop()的顺序,应该在循环之间就pop()出去,否则之后q.front()可能会被更新、无法检索到正确的fxfy

参考代码:

#include<bits/stdc++.h>
using namespace std;
int n,m;
int x,y;
const int maxn=400+5;
int d1[8]={-1,-2,-2,-1,1,2,2,1};
int d2[8]={-2,-1,1,2,-2,-1,1,2};
struct node{
    int x;
    int y;
    int num;
};
int a[maxn][maxn];
queue <node> q;
int main(){
    cin>>n>>m>>x>>y;
    q.push(node{x,y,0});
    a[x][y]=-2;
    while (!q.empty()){
        
        int fx=q.front().x;
        int fy=q.front().y;
        int num=q.front().num;
        q.pop();
        for (int i=0; i<8; i++){
            int nx=fx+d1[i];
            int ny=fy+d2[i];
            if (!a[nx][ny] && nx>=1 && nx<=n && ny>=1 &&ny<=m){
                a[nx][ny]=num+1;
                q.push(node{nx,ny,num+1});
            }
        }
        
    }
    for (int i=1; i<=n; i++){
        for (int j=1; j<=m; j++)
            if (a[i][j]==0){
                cout<<-1<<" ";
            }
            else if (a[i][j]==-2){
                cout<<0<<" ";
            }
            else 
                cout<<a[i][j]<<" ";
            cout<<endl;
    }
    system("pause");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值