|
发表于 2023-7-23 11:25:35
|
显示全部楼层
根据你提供的代码,我看到你正在尝试解决洛谷上的问题 P5318。对于你提到的问题,你认为深度优先搜索(DFS)并没有搜索到最底层。
经过仔细分析你的代码,我发现在DFS函数中确实存在一个问题。在递归调用dfs(p[x][ i])之前,你没有将u[p[x][ i]]标记为已访问(即设置为1),导致在某些情况下会出现重复访问节点的情况。为了解决这个问题,你需要在递归调用之前将u[p[x][ i]]设置为1,表示已访问。
以下是修改后的代码:
- #include <bits/stdc++.h>
- using namespace std;
- int n, m, x, y;
- vector<int> p[100009];
- queue<int> q;
- int u[100009];
- void dfs(int x) {
- cout << x << ' ';
- for (int i = 0, z = p[x].size(); i < z; i++) {
- if (!u[p[x][ i]]) {
- u[p[x][ i]] = 1;
- dfs(p[x][ i]);
- }
- }
- }
- int main() {
- memset(u, 0, sizeof(u));
- cin >> n >> m;
- for (int i = 0; i < m; i++) {
- cin >> x >> y;
- p[x].push_back(y);
- p[y].push_back(x);
- }
- for (int i = 1; i <= n; i++) {
- sort(p[ i].begin(), p[ i].end());
- }
- u[1] = 1;
- dfs(1);
- cout << endl;
- memset(u, 0, sizeof(u));
- u[1] = 1;
- q.push(1);
- while (!q.empty()) {
- int x = q.front();
- q.pop();
- cout << x << ' ';
- for (int i = 0, z = p[x].size(); i < z; i++) {
- if (!u[p[x][ i]]) {
- u[p[x][ i]] = 1;
- q.push(p[x][ i]);
- }
- }
- }
- cout << endl;
- return 0;
- }
复制代码
以上修改后的代码应该能够解决你遇到的问题。希望对你有所帮助。如果还有其他问题,请随时提问。
如果问题已经解决,请设置最佳答案 |
|