改成广度优先搜索bool dfs(int to_x, int to_y, int box_x, int box_y, int people_x, int people_y) { visit2[people_x][people_y] = 1; if (to_x == people_x && to_y == people_y) { flag1 = true; return true; } if (!flag1) { for (int i = 0; i < 4; i++) { int xx = people_x + dx[i]; int yy = people_y + dy[i]; if (xx<1 || yy<1 || xx>n || yy>m || (xx == box_x && yy == box_y) || board[xx][yy] == 1 || visit2[xx][yy]) continue; dfs(to_x, to_y, box_x, box_y, xx, yy); if (flag1) return true; } } return false; }
时间: 2024-04-09 21:33:49 浏览: 130
c/c++语言实现的广度优先搜索算法
5星 · 资源好评率100%
你想将这段代码改成广度优先搜索的形式,是吗?下面是改写后的代码:
```cpp
bool bfs(int to_x, int to_y, int box_x, int box_y, int people_x, int people_y)
{
queue<pair<int, int>> q;
q.push({people_x, people_y});
visit2[people_x][people_y] = 1;
while (!q.empty())
{
pair<int, int> cur = q.front();
q.pop();
if (cur.first == to_x && cur.second == to_y)
{
flag1 = true;
return true;
}
for (int i = 0; i < 4; i++)
{
int xx = cur.first + dx[i];
int yy = cur.second + dy[i];
if (xx < 1 || yy < 1 || xx > n || yy > m || (xx == box_x && yy == box_y) || board[xx][yy] == 1 || visit2[xx][yy])
continue;
q.push({xx, yy});
visit2[xx][yy] = 1;
}
}
return false;
}
```
这个改写后的代码使用了队列来实现广度优先搜索,每次取出队列中的一个点,然后将它周围未访问过的点加入队列。如果找到目标点,则返回true,否则返回false。注意,在每次将点加入队列之前需要将其标记为已访问。希望这个改写对你有帮助!
阅读全文