算法笔记:BFS与DFS 书上给的BFS,现在对BFS进行改写为DFS

给定一个n*m大小的迷宫,其中*代表墙,而.代表平地,S代表起点,T代表终点。移动过程中,如果当前位置是(x,y)下标从0开始,且每次只能上下左右(x,y+1)、(x,y-1)、(x-1,y)、(x+1,y)四个位置的平地,求起点S到终点T的最小步数。

void BFS_dfs(int step,int x,int y)此函数是bfs改为dfs的函数:

#include "stdafx.h"
#include<vector>
#include<iostream>
#include<stdio.h>
#include<queue>

using namespace std;
//变量声明
const int maxn = 1000;
struct node {
    int x, y;        //位置x,y
    int step;        //step为起点S到终点T的最小步数

}S, T, Node;        //S为起点,T为终点,Node为临时结点
int n, m;
char maze[maxn][maxn];        //迷宫信息
bool inq[maxn][maxn] = { false };    //记录位置(x,y)是否已入队
int X[4] = { 0,0,1,-1 };
int Y[4] = { 1,-1,0,0 };
bool test(int x, int y) {
    if (x >= n || x < 0 || y >= m || y < 0) return false;    //越界
    if (maze[x][y] == '*')return false;                        //墙壁
    if (inq[x][y] == true)return false;                        //已入队
    return true;
}
int BFS() {
    queue<node> q;
    q.push(S);
    inq[S.x][S.y] = true;
    while (!q.empty()) {
        node top = q.front();
        q.pop();
        if (top.x == T.x && top.y == T.y) {
            return top.step;
        }
        for (int i = 0;i < 4;i++) {
            int newX = top.x + X[i];
            int newY = top.y + Y[i];
            if (test(newX, newY)) {
                Node.x = newX;
                Node.y = newY;
                Node.step = top.step + 1;
                //printf("%d\n", Node.step);
                q.push(Node);
                inq[newX][newY] = true;
            }
        }
    }
    return -1;
}
int min_step = -1;
void BFS_dfs(int step,int x,int y) {
    inq[S.x][S.y] = true;
    if (x == T.x&&y == T.y) {
        if (step>=0&&step < min_step) {
            min_step = step;            //更新最小步数
        }
        return;
    }
    //if (test(x, y) == false) return;
    for (int i = 0;i < 4;i++) {
        int newx = x + X[i];
        int newy = y + Y[i];
        if (test (newx,newy)) {
            inq[newx][newy] = true;
            BFS_dfs(step + 1, newx, newy);
        }
    }
    return;
}

int main() {

    scanf_s("%d%d", &n, &m);
    for (int i = 0;i < n;i++) {
        getchar();
        for (int j = 0;j < m;j++) {
            maze[i][j] = getchar();

        }
        maze[i][m + 1] = '\0';
    }
    scanf_s("%d%d%d%d", &S.x, &S.y, &T.x, &T.y);
    BFS_dfs(0, S.x, S.y);
    //S.step = 0;
    //printf("%d", BFS();
    printf("%d", min_step);

    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值