用代码编写用邻接矩阵实现DFS和BFS
时间: 2023-04-06 18:02:59 浏览: 65
可以的,以下是用邻接矩阵实现DFS和BFS的代码:
DFS:
```
void DFS(int v, bool visited[], int** graph, int n) {
visited[v] = true;
cout << v << " ";
for (int i = 0; i < n; i++) {
if (graph[v][i] && !visited[i]) {
DFS(i, visited, graph, n);
}
}
}
void DFS(int start, int** graph, int n) {
bool* visited = new bool[n];
for (int i = 0; i < n; i++) {
visited[i] = false;
}
DFS(start, visited, graph, n);
delete[] visited;
}
```
BFS:
```
void BFS(int start, int** graph, int n) {
bool* visited = new bool[n];
for (int i = 0; i < n; i++) {
visited[i] = false;
}
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int v = q.front();
q.pop();
cout << v << " ";
for (int i = 0; i < n; i++) {
if (graph[v][i