深度优先搜索
#include <vector>
#include <iostream>
using namespace std;
#define MAX 5
char node[MAX];
int node_edge[MAX][MAX];
vector<char> dfs;
bool visited[MAX];
void InPut()
{
cout << "Input nodes :" << endl;
for (int i = 0; i < MAX; i++)
{
cin >> node[i];
}
cout << "Input edges:" << endl;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
cin >> node_edge[i][j];
}
}
memset(visited, false, MAX);
}
void DFS()
{
char n = node[0];
dfs.push_back(n);
while (!dfs.empty())
{
char ch = dfs.back();
int index;
for (index = 0; index < MAX; index++)
{
if (node[index] == ch)
{
break;
}
}
if (visited[index] == true)
{
int i;
for (i = 0; i < MAX; i++)
{
if (node_edge[index][i] == 1 && visited[i] == false)
{
dfs.push_back(node[i]);
break;
}
}
if (i == MAX)
{
dfs.pop_back();
}
continue;
}
cout << ch << " ";
visited[index] = true;
}
}
int main()
{
InPut();
DFS();
return 0;
}
广度优先搜索
#include <queue>
#include <iostream>
using namespace std;
#define MAX 5
char node[MAX];
int node_edge[MAX][MAX];
queue<char> bfs;
bool visited[MAX];
void InPut()
{
cout << "Input nodes :" << endl;
for (int i = 0; i < MAX; i++)
{
cin >> node[i];
}
cout << "Input edges:" << endl;
for (int i = 0; i < MAX; i++)
{
for (int j = 0; j < MAX; j++)
{
cin >> node_edge[i][j];
}
}
memset(visited, false, MAX);
}
void BFS()
{
char n = node[0];
bfs.push(n);
while (!bfs.empty())
{
char ch = bfs.front();
bfs.pop();
int index;
for (index = 0; index < MAX; index++)
{
if (node[index] == ch)
{
break;
}
}
if (visited[index] == true)
{
continue;
}
cout << ch << " ";
visited[index] = true;
for (int i = 0; i < MAX; i++)
{
if (node_edge[index][i] == 1 && visited[i] == false)
{
bfs.push(node[i]);
}
}
}
}
int main()
{
InPut();
BFS();
return 0;
}
|