码迷,mamicode.com
首页 > 其他好文 > 详细

数据结构之图 Part3 – 1 遍历

时间:2014-08-09 18:17:38      阅读:232      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   数据   for   2014   

DFS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LH.GraphConsole
{
    class Program
    {
        private static bool[] visited;

        static void Main(string[] args)
        {
            DFSTranverse();
        }

        private static void DFSTranverse()
        {
            int vertexNumber = 9;
            int edgeNumber = 15;
            Graph graph = new Graph(vertexNumber, edgeNumber);

            graph.Vertexs[0] = "A";
            graph.Vertexs[1] = "B";
            graph.Vertexs[2] = "C";
            graph.Vertexs[3] = "D";
            graph.Vertexs[4] = "E";
            graph.Vertexs[5] = "F";
            graph.Vertexs[6] = "G";
            graph.Vertexs[7] = "H";
            graph.Vertexs[8] = "I";

            graph.Edges[0, 1] = 1;
            graph.Edges[0, 5] = 1;

            graph.Edges[1, 2] = 1;
            graph.Edges[1, 8] = 1;
            graph.Edges[1, 6] = 1;

            graph.Edges[2, 3] = 1;
            graph.Edges[2, 8] = 1;

            graph.Edges[3, 8] = 1;
            graph.Edges[3, 6] = 1;
            graph.Edges[3, 7] = 1;
            graph.Edges[3, 4] = 1;

            graph.Edges[4, 7] = 1;
            graph.Edges[4, 5] = 1;

            graph.Edges[5, 6] = 1;

            graph.Edges[6, 7] = 1;

            visited = new bool[vertexNumber];
            for (int i = 0; i < vertexNumber; i++)
            {
                if (!visited[i])
                {
                    DFS(graph, i);
                }
            }
        }
        private static void DFS(Graph graph, int vertexIndex)
        {
            visited[vertexIndex] = true;
            Console.WriteLine("Visit vertex index: " + vertexIndex);

            var size = graph.Vertexs.Count();
            for (int i = 0; i < size; i++)
            {
                if (graph.Edges[vertexIndex, i] == 1 && !visited[i])
                {
                    DFS(graph, i);
                }
            }
        }
    }
}

输出结果:
bubuko.com,布布扣 

数据结构之图 Part3 – 1 遍历,布布扣,bubuko.com

数据结构之图 Part3 – 1 遍历

标签:style   blog   http   color   io   数据   for   2014   

原文地址:http://www.cnblogs.com/bnbqian/p/3901256.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!