C++深度优先算法以及广度优先算法求解经典例题

〈一〉广度优先算法求解路径问题

int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};

bool in(int x,int y){

 return 0 <= x && x < n && 0 <= y && y < m;

}

struct node{

 int x,y,d;

 node(int xx,int yy,int dd){

  x = xx;

  y = yy;

  d = dd;

 }

};

int bfs(int sx,int sy){

 queue<node> q;

 q.push(node(sx,sy,0));

 vis[sx][sy] = true;

 while(!q.empty()){

  node now = q.front();

  q.pop();

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

   int tx = now.x + dir[i][0];

   int ty = now.y + dir[i][1];

   if(int(tx,ty) && maze[tx][ty] != '*' && !vis[tx][ty]){

    if(maze[tx][ty] == 'T'){

     return now.d + 1;

    }else{

     vis[tx][ty] = true;

     q.push(node(tx,ty,now.d + 1));

    }

   }

  }

 }

 return -1;

〈二〉深度优先算法求解最短步数

//针对深度优先算法之中里面查找最短路径的求解计算

#include<iostream>

#include<string>

using namespace std;

int n,m;

string maze[110];

bool vis[110][110];

int ans= 100000000;

int dir[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};

bool in(int x,int y){

 return 0 <= x && x < n&& 0<=y&&y <m;

}

void dfs(int x,int y ,int step){

 if(maze[x][y] == 'T'){

  if(step < ans){

   ans = step;

  }

  return;

 }

 vis[x][y] = 1;

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

  int tx = x + dir[i][0];

  int ty = y + dir[i][1];

  if(in{tx,ty} && maze[tx][ty] != '*' && !vis[tx][ty]){

   dfs(tx,ty,step + 1);

  }

 }

 vis[x][y] = 0;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值