深度优先遍历DFS是针对树中某个节点首先朝一个子节点方向一直遍历到叶子节点,然后通过递归(或者压栈)将所有节点遍历完成。而广度优先遍历BFS是对一个节点的子节点全部遍历完成后继续遍历子节点的所有子节点,最终完成整个遍历过程。因此,我们将这两种算法应用到矩阵的元素遍历上。(时间复杂度较大>O(n^2)可优化)
#include<iostream>
#include<queue>
#include<utility>
#include<cmath>
#include<windows.h>
using namespace std;
int num[1000][1000];
bool reach[1000][1000];
int row, col;//记录矩阵行列
void init();
void bfs(pair<int,int>&obj);
void dfs(pair<int, int>&obj);
void part_dfs(pair<int,int>&obj);
void init_reach();
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cin >> row >> col;
init();
pair<int, int>begin;
cout << "please input begin vertex." << endl;
cin >> begin.first >> begin.second;
cout << "BFS:\n";
bfs(begin);
cout << "\nDFS:\n";
dfs(begin);
system("pause");
return 0;
}
void init()
{
for (int i = 1; i <= row;++i)
for (int j = 1; j <= col; ++j)
cin >> num[i][j];
}
void init_reach()
{
for (int i = 1; i <= row; ++i)
for (int j = 1; j <= col; ++j)
reach[i][j] = false;
}
void bfs(pair<int, int>&obj)
{
init_reach();
queue<pair<int,int>>q;
q.push(obj);
reach[obj.first][obj.second] = true;
while (!q.empty())
{
pair<int, int>temp = q.front();
q.pop();
cout << num[temp.first][temp.second] << " ";
for (int i = 1; i <= row;++i)
for (int j = 1; j <= col; ++j)
{
if (reach[i][j]) continue;
else if (abs(temp.first - i) == 1 && j == temp.second ||
abs(temp.second - j) == 1 && i == temp.first)
{
pair<int, int>*p = new pair<int, int>(i,j);
q.push(*p);
reach[i][j] = true;
delete p;
}
}
}
}
void dfs(pair<int, int>&obj)
{
init_reach();
part_dfs(obj);
}
void part_dfs(pair<int, int>&obj)
{
reach[obj.first][obj.second] = true;
cout << num[obj.first][obj.second] << " ";
for (int i = 1; i <= row; ++i)
for (int j = 1; j <= col; ++j)
{
if (reach[i][j]) continue;
else if (abs(obj.first - i) == 1 && j == obj.second ||
abs(obj.second - j) == 1 && i == obj.first)
{
pair<int, int>*p = new pair<int, int>(i, j);
part_dfs(*p);
delete p;
}
}
}
程序测试结果如下: