洛谷P1363_迷宫dfs搜索的船新版本

本文介绍了一种改进的迷宫深度优先搜索算法实现。新版本使用行号和列号作为形参,并通过访问值记录每个节点的状态。文章提供了完整的C++代码实现,包括输入迷宫布局和判断是否可达的逻辑。

以前用迷宫dfs搜索的形参都是m(m = row * 列数 + col),然后依次搜索

*****************************弱************蒟蒻****************************************

船新版本:

(1)形参就是行号和列号

(2)vis[x][y][0]记录该点的访问值的row,vis[x][y][1]记录该点访问值的col,初始化INF

(3)算得modn的行号tx和modm的列号ty

(4)如果该点不能走则返回0

(5)如果该点能走,但访问值不为初始值INF,即已经走过了

    若该点的访问值为x和y,那么返回0

    若该点的访问值不为x和y,那么则认为到达了无穷远,返回1

(6)否则记录访问值,继续从4个方向扩展

*********************************************************************************************

//dfs搜迷宫船新版本
#include <cstdio>

using namespace std;

const int maxn = 2000;
const int INF = 99999999;

int n, m, S;
int vis[maxn][maxn][2];
int a[maxn][maxn];
char str[maxn];
int dx[4]={-1, 1, 0, 0};
int dy[4]={0, 0, -1, 1};

bool dfs(int x, int y)
{//如果一个位置的访问值不等于当前x和y的值则到达无穷大
    int tx = (x % n + n) % n;
    int ty = (y % m + m) % m;
    if(a[tx][ty]) return 0;
    if(vis[tx][ty][0] != INF)
        return vis[tx][ty][0]!=x || vis[tx][ty][1]!=y;
    vis[tx][ty][0] = x;//访问值记录
    vis[tx][ty][1] = y;
    for(int i = 0; i < 4; ++i)
        if(dfs(x+dx[i], y+dy[i]))
            return 1;
    return 0;
}

int main()
{
    while(~scanf("%d %d", &n, &m))
    {
        int i, j, sx, sy;
        for(i = 0; i < n; ++i)
        {
            scanf("%s", str);
            for(j = 0; j < m; ++j)
            {
                vis[i][j][0] = INF;//初始值
                if(str[j] == 'S')
                {
                    a[i][j] = 0;
                    sx = i;
                    sy = j;
                }
                else if(str[j] == '#') a[i][j] = 1;
                else a[i][j] = 0;
            }
        }
        if(dfs(sx, sy)) printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}

### 迷宫题的DFS解决方案 深度优先搜索(Depth First Search, DFS)是一种常用的图遍历算法,在解决迷宫题时非常有效。以下是基于提供的引用以及专业知识整理的一个完整的解决方案。 #### 1. 基本思路 DFS的核心在于通过递归的方式探索所有的可能路径,直到找到目标位置或者确认无路可走为止。对于迷宫题来说,通常会定义一个二维数组表示地图,其中 `0` 表示可以通过的位置,而 `1` 或其他标记则代表障碍物[^1]。 为了实现这一功能,可以采用如下策略: - 定义四个移动方向:上、下、左、右。 - 使用递归来尝试每一步的可能性,并在遇到死胡同时返回前一状态继续探索新的分支[^4]。 #### 2. 实现细节 下面给出了一种典型的C++代码实现方式: ```cpp #include <iostream> #include <vector> using namespace std; // 方向数组,分别对应上下左右四个方向 const vector<pair<int, int>> directions = { { -1, 0 }, // 上 { 1, 0 }, // 下 { 0, -1 }, // 左 { 0, 1 } // 右 }; bool isValidMove(int newRow, int newCol, const vector<vector<int>>& maze, vector<vector<bool>>& visited) { int rows = maze.size(); int cols = maze[0].size(); return newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && !maze[newRow][newCol] && !visited[newRow][newCol]; } bool dfs(vector<vector<int>>& maze, vector<vector<bool>>& visited, pair<int, int> currentPos, pair<int, int> target) { if (currentPos.first == target.first && currentPos.second == target.second){ return true; } for(auto& dir : directions){ int newRow = currentPos.first + dir.first; int newCol = currentPos.second + dir.second; if(isValidMove(newRow, newCol, maze, visited)){ visited[newRow][newCol] = true; if(dfs(maze, visited, make_pair(newRow, newCol), target)){ return true; } // 如果该条路径不通,则回溯到之前的状态并尝试另一条路径 } } return false; } int main(){ vector<vector<int>> maze = { {0, 1, 0, 0}, {0, 1, 0, 1}, {0, 0, 0, 0}, {0, 1, 1, 0} }; pair<int,int> start = {0,0}; pair<int,int> end = {3,3}; int nRows = maze.size(); int nCols = maze[0].size(); vector<vector<bool>> visited(nRows, vector<bool>(nCols, false)); bool result = dfs(maze, visited, start, end); cout << (result ? "Path found!" : "No path exists.") << endl; return 0; } ``` 上述程序中包含了几个重要部分: - **方向数组**用于指定每次可以从当前位置出发到达的新坐标; - **isValidMove函数**用来判断下一步是否合法; - **dfs函数**实现了核心逻辑,即不断深入直至达到目的地或穷尽所有可能性后退出[^2]。 #### 3. 关键点解析 - **边界条件**: 需要特别注意越界情况以及访过的节点不能再重复进入以免陷入无限循环[^3]。 - **回溯机制**: 当某一条路线无法通达终点时,应回退至上一层重新选择未被尝试的方向前进。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值