图的广度深度优先遍历(入门级)


改编自原文:https://www.cnblogs.com/nr-zhang/p/11236369.html
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    public class Graph
    {
        public int[,] arcs;
        public string[] arrays;
        public int pointNum;
        public int[] visited;

        public Graph(string[] arrays)
        {
            this.pointNum = arrays.Length;
            arcs = new int[pointNum,pointNum];
            visited = new int[pointNum];
            this.arrays = arrays;           
            for (int i = 0; i < pointNum; i++)
            {
                for (int j = 0; j < pointNum; j++)
                {
                    arcs[i,j] = 0;
                }
            }
        }
        public void addEdge(int a,int b)
        {
            if (a == b)
            {
                return;
            }
            arcs[a,b] = 1;
            arcs[b,a] = 1;

        }
        public void dfsVisit(int i)
        {
            visited[i] = 1;
            Console.WriteLine(i);
            for (int j = 0; j < pointNum; j++)
            {
                if(arcs[i,j]==1 && visited[j] == 0)
                {
                 
                    dfsVisit(j);
                  
                }
               
            }

        }
        
        public void bfsVisit(int i)
        {
            Queue dq = new Queue();
            dq.Enqueue(i);

            while (dq.Count>0)
            {

                var d1 = dq.Dequeue();
                var p = (int)d1;
                visited[p] = 1;
                Console.WriteLine(p);
                for (int j = 0; j < pointNum; j++)
                {
                    if (arcs[p, j] == 1 && visited[j] == 0)
                    {
                        visited[j] = 1;
                        dq.Enqueue(j);
                        
                    }

                }

            }

        

        }

        public static void testDBFS()
        {
            var array1 = new string[] { "景点0", "景点1", "景点2", "景点3", "景点4", "景点5", "景点6", "景点7", "景点8", "景点9", "景点10" };
            var graph = new Graph(array1);
            graph.addEdge(0, 1);
            graph.addEdge(0, 2);
            graph.addEdge(0, 3);
            graph.addEdge(0, 4);
            graph.addEdge(1, 4);
            graph.addEdge(1, 7);
            graph.addEdge(1, 9);
            graph.addEdge(3, 5);
            graph.addEdge(3, 6);
            graph.addEdge(4, 5);
            graph.addEdge(7, 8);
            graph.addEdge(7, 10);
           
            graph.dfsVisit(0);
           // graph.bfsVisit(0);
            Console.Read();
        }

    }
}

 

posted @ 2020-09-17 09:47  陈群松  阅读(29)  评论(0)    收藏  举报