bfs+bfs/dfs hdu 1254 推箱子1

本文详细介绍了HDU 1254推箱子问题的解决方法,重点探讨了使用宽度优先搜索(BFS)和深度优先搜索(DFS)的策略。通过这两种算法,解题者可以找到如何在限定步数内将箱子推到目标位置的最优路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.hdu.edu.cn/showproblem.php?pid=1254

推箱子



#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
/*
BFS+BFS/DFS,第二个用于判断是否能移动到可以推得位置,因为矩阵很小所以就
DFS也不担心 TLE了,
注意第二组数据,箱子路径可能会重复,所以标记vis要开思维同时记录箱子和人的
位置
*/
using namespace std;
int maze[7][7],move[][2]={0,1,1,0,0,-1,-1,0},dex,dey;
int dvis[7][7];
int m,n;
struct node
{
    int px,py,bx,by;
}p;

bool ok(int x,int y)
{
    if(x<0||x>=m||y<0||y>=n||maze[x][y]==1)
        return 0;
    return 1;
}
bool connect(int bx,int by, in
### C++ 中使用 BFS 和 For 循环替代 DFS 的实现 在解决网格类问题时,广度优先搜索 (BFS) 可作为深度优先搜索 (DFS) 的有效替代方案。对于岛屿等问题而言,可以利用队列来管理待访问的位置,并通过 `for` 循环迭代处理这些位置。 #### 岛屿数量问题的 BFS 解决方案 下面是一个基于 BFS 来计算岛屿数量的例子: ```cpp #include <vector> #include <queue> using namespace std; class Solution { public: int numIslands(vector<vector<char>>& grid) { if (grid.empty() || grid[0].empty()) return 0; int rows = grid.size(); int cols = grid[0].size(); int islands = 0; vector<pair<int, int>> directions{{0,-1},{-1,0},{0,1},{1,0}}; for (int r = 0; r < rows; ++r){ for (int c = 0; c < cols; ++c){ if (grid[r][c] == '1'){ ++islands; queue<pair<int, int>> q; q.push({r,c}); while (!q.empty()){ auto [row, col] = q.front(); q.pop(); // 如果当前位置已经被标记,则跳过 if(grid[row][col]=='0') continue; // 将当前陆地标记为已访问 grid[row][col]='0'; // 对四个方向上的相邻节点进行探索 for(auto& dir : directions){ int newRow = row + dir.first; int newCol = col + dir.second; // 检查边界条件以及是否是未访问过的土地 if(newRow >= 0 && newRow < rows && newCol >= 0 && newCol < cols && grid[newRow][newCol] == '1') q.push({newRow,newCol}); } } } } } return islands; } }; ``` 此代码片段展示了如何使用 BFS 方法遍历整个地图并统计岛屿的数量。每当遇到一个新的岛屿部分(即值为 `'1'`),就启动一次新的 BFS 查找过程直到该岛完全被淹没为止。在此过程中,所有属于同一座岛屿的部分都会被设置成水 (`'0'`) 以防止重复计数[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值