#include <iostream> using namespace std; const int MAXN = 10005; int stack[MAXN], top = -1; void push(int x) { stack[++top] = x;} int pop() { return stack[top--];} bool empty() { return top == -1;} void dfs(int u, int graph[][MAXN], bool visited[], int farthest[]) { push(u); visited[u] = true; while (!empty()) { int v = pop(); for (int i = 0; i < MAXN; i++) { if (graph[v][i] && !visited[i]) { visited[i] = true; push(i); farthest[i] = farthest[v] + 1; } } } } int main() { int n, m; cin >> n >> m; int graph[MAXN][MAXN] = {0}; for (int i = 0; i < m; i++) { int u, v; cin >> u >> v; graph[u][v] = 1; } int farthest[MAXN] = {0}; for (int i = 0; i < n; i++) { bool visited[MAXN] = {false}; dfs(i, graph, visited, farthest); } for (int i = 0; i < n; i++) { cout<< farthest[i] ; } return 0; }这个代码有溢出问题,帮我修改
时间: 2024-01-20 08:04:40 浏览: 98
#include <iostream>
这个代码定义的图是一个邻接矩阵,数组大小为MAXN * MAXN,当n较大时,可能会导致内存溢出。另外,在dfs搜索时,如果出现死循环,也可能导致栈溢出。以下是修改后的代码,对于dfs的实现,使用递归代替栈实现,同时在搜索前添加了一个visited判断,避免重复搜索已经访问过的节点。
```c++
#include <iostream>
using namespace std;
const int MAXN = 10005;
int farthest[MAXN] = {0};
bool visited[MAXN] = {false};
void dfs(int u, int graph[][MAXN], int depth) {
visited[u] = true;
farthest[u] = depth;
for (int i = 0; i < MAXN; i++) {
if (graph[u][i] && !visited[i]) {
dfs(i, graph, depth + 1);
}
}
}
int main() {
int n, m;
cin >> n >> m;
int graph[MAXN][MAXN] = {0};
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
graph[u][v] = 1;
}
for (int i = 0; i < n; i++) {
if (!visited[i]) {
dfs(i, graph, 0);
}
}
for (int i = 0; i < n; i++) {
cout << farthest[i] << endl;
}
return 0;
}
```
阅读全文