Answer the question
In order to leave comments, you need to log in
What is the problem with breadth and depth traversal?
There is a program that performs breadth and depth traversal to find a path between vertices.
#include <vector>
#include <locale.h>
#include <queue>
#include <Windows.h>
#include <set>
#include <iostream>
#include <fstream>
using namespace std;
UINT BFS(UINT begin, UINT vertex, UINT n, const vector<vector<int>> &graph)
{
queue<int> q;
q.push(begin);
set<int> gray;
while (!q.empty())
{
UINT v = q.front();
q.pop();
gray.insert(v);
if (v == vertex)
return 1;
for (UINT i = 0; i < n; i++)
if (graph[v][i])
q.push(i);
if (q.empty())
return 0;
}
for (UINT j : gray);
}
UINT DFS(UINT u, UINT vertex, UINT n, const vector<vector<int>> &graph, set<int> &gray, set<int> &black)
{
gray.insert(u);
for (UINT i = 0; i < n; i++)
if (graph[u][i])
{
if (i == vertex)
return 1;
int is_black = black.count(i), is_gray = gray.count(i), is_white = 0;
if (!is_black || !is_gray)
is_white = 1;
if (is_white)
if (DFS(i, vertex, n, graph, gray, black))
return 1;
}
gray.erase(u);
black.insert(u);
return 0;
}
void main()
{
UINT one = 0, two = 0;
setlocale(LC_ALL, "");
ifstream get_content("in.txt");
if (get_content)
{
UINT vertex, edge;
get_content >> vertex >> edge;
vector<vector<int>> graph;
graph.assign(vertex, vector<int>(vertex));;
UINT one, two;
for (UINT i = 0; i < edge; i++)
{
UINT one, two;
get_content >> one >> two;
graph[one][two] = 1;
}
printf_s("Введите две вершины: ");
cin >> one;
cin >> two;
set<int> gray, black;
UINT b = DFS(one, two, vertex, graph, gray, black);
b ? printf_s("Путь есть\n") : printf_s("Пути нет\n");
b = BFS(one, two, vertex, graph);
b ? printf_s("Путь есть\n") : printf_s("Пути нет\n");
}
else
printf_s("Не удалось открыть файл");
return;
}
Answer the question
In order to leave comments, you need to log in
In BFS, you don't check that a vertex is labeled, and you always queue the vertex. And there is some unnecessary left cycle at the end. The search loops endlessly and eats up all the memory. DFS seems to be correct (there are many complaints about the style, really).
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question