图的入门之的深度遍历

PS:终于开始图的学习之旅了,先来个开胃小菜,图的深度遍历(DFS),个人代码如下:

#include<stdio.h>
#include<iostream>
using namespace std;

void dfs(char a[][5], int row, int col, int r, int c, const char tag = '#')
{
	if(r < 0 || r > row - 1 || c < 0 || c > col - 1) return;
	if(tag == a[r][c]) return ;	<span style="white-space:pre">	</span>//访问过的点不需要再访问了
	cout<< a[r][c] << " ";
	a[r][c] = tag;				//访问过的点用#号来标记
	for(int i = -1; i <= 1; ++i)
		for(int j = -1; j <= 1; ++j)
		{
			if(i == 0 && j == 0) continue;
			dfs(a, row, col, r+i, c+j);
		}
}

int main()
{
	const int COL = 5;
	int row;
	cin >> row ;
	char a[row][COL];
	for(int i = 0; i < row; ++i)
		scanf("%s", a[i]);
	dfs(a, row, COL, 0, 0);
}

输入和输出:

图的广度遍历(BFS), 个人代码如下:

#include <iostream>
#include <queue>
using namespace std;

const int ROW = 3;
const int COL = 5;
const int dr[] = {1, -1, 0, 0};
const int dc[] = {0, 0, -1, 1};

void BFS(char a[][COL])
{
	queue<pair<int, int> > que;
	pair<int, int> par;
	int row, col;
	que.push(make_pair(0,0));
	while(!que.empty())
	{
		//访问周边的节点,放入到队列中
		par = que.front(); que.pop();
		for(int i = 0; i < 4; ++i)
		{
			row = par.first; row = row + dr[i];
			col = par.second; col = col + dc[i];
			if(row < 0 || row >= ROW || col < 0 || col >= COL) continue;
			que.push(make_pair(row, col));
		}
		//输出访问的点
		if(a[par.first][par.second] == '#') continue;<span style="white-space:pre">	</span>//访问过的点用#标记
		cout<< a[par.first][par.second] <<endl;
		a[par.first][par.second] = '#';
	}
}

int main()
{
	char a[ROW][COL];
	memset(a, 0, sizeof(a));
	for(int i = 0; i < ROW; ++i)
		scanf("%s", a[i]);

	BFS(a);
	return 0;
}

输入:

abcde

fghij

opqrs

《图的入门之的深度遍历》
《图的入门之的深度遍历》

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/hepeng1341022/article/details/42784857
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞