上篇文章介绍了深度优先遍历,同时也介绍了广度优先遍历的思想,这里直接上代码:
using System;
using System.Collections.Generic;
using static System.Console;
namespace 图的广度优先遍历
{
class Node
{
public int item;
public Node next;
public Node(int a)
{
item = a;
next = null;
}
}
class GraphLink
{
public Node first;
public Node last;
public GraphLink()
{
first = null;
last = null;
}
public void Insert(int a)
{
Node newnode = new Node(a);
if(first == null)
{
first = newnode;
last = newnode;
}
else
{
last.next = newnode;
last = newnode;
}
}
public void Print()
{
Node current = first;
while(current != null)
{
Write("[" + current.item + "]");
current = current.next;
}
WriteLine();
}
}
class Program
{
public static int[] run = new int[9];
public static GraphLink[] head = new GraphLink[9];
public const int MaxSize = 10;
public static Queue<int> queue = new Queue<int>();
public static void BFS(int current)
{
Node temp;
queue.Enqueue(current);
run[current] = 1;
Write("[" + current + "]");
while( queue.Count > 0)
{
current = queue.Dequeue();
temp = head[current].first;
while(temp != null)
{
if(run[temp.item] == 0)
{
queue.Enqueue(temp.item);
run[temp.item] = 1;
Write("[" + temp.item + "]");
}
temp = temp.next;
}
}
}
static void Main(string[] args)
{
int[,] data = { { 1, 2 }, { 2, 1 }, { 1, 3 }, { 3, 1 }, { 2,4},
{ 4,2},{ 2,5},{ 5,2},{ 3,6},{ 6,3},
{ 3,7},{ 7,3},{ 4,5},{ 5,4},{ 6,7},
{7,6},{ 5,8},{ 8,5},{ 6,8},{ 8,6} };
int DataNum;
int i, j;
WriteLine("图的邻接链表内容:");
for ( i = 1; i < 9; i++)
{
run[i] = 0;
head[i] = new GraphLink();
Write("顶点" + i + "=>");
for ( j = 0; j < 20; j++)
{
if(data[j,0] == i)
{
DataNum = data[j, 1];
head[i].Insert(DataNum);
}
}
head[i].Print();
}
WriteLine("广度优先遍历:");
BFS(1);
WriteLine();
ReadKey();
}
}
}
真的跟二叉树的层序遍历一模一样哈~真喜欢优雅的队列