BFS в матрице смежности - PullRequest
       14

BFS в матрице смежности

0 голосов
/ 26 апреля 2018

Используя следующий код, когда я вызываю метод bfs, я получаю результат 123465247.Как мне объявить и использовать переменную visited, чтобы вывод стал 1234657?

class Graph
{
    public int[] graph1VertexList = new int[] {1,2,3,4,5,6,7};
    public int[,] graph1=new int[7,7];

    public Graph()
    {
        //for the graph1
        graph1[0, 1] = 1;
        graph1[0, 2] = 1;
        graph1[1, 3] = 1;
        graph1[2, 5] = 1;
        graph1[3, 4] = 1;
        graph1[4, 1] = 1;
        graph1[5, 3] = 1;
        graph1[5, 6] = 1;
    }


    public void bfs()
    {
        Console.Write(graph1VertexList[0]);//print the first value
        for(int i = 0; i < graph1VertexList.Length; i++)
        {
            for(int z = 0; z < graph1VertexList.Length; z++)
            {
                if (graph1[i, z] == 1)
                {
                    Console.Write(graph1VertexList[z]);
                }
            }
        }
    }

}

1 Ответ

0 голосов
/ 26 апреля 2018

Вы должны ввести логический массив, чтобы указать, была ли определенная вершина уже посещена. Кроме того, массив должен быть проверен, если ребро сопровождается и обновляется после этого. Это можно сделать следующим образом.

public int[] graph1VertexList = new int[] { 1, 2, 3, 4, 5, 6, 7 };
public int[,] graph1 = new int[7, 7];

public bool[] visited = new bool[7]; // new array, initialized to false

public void bfs()
{
    Console.Write(graph1VertexList[0]);//print the first value
    for (int i = 0; i < graph1VertexList.Length; i++)
    {
        for (int z = 0; z < graph1VertexList.Length; z++)
        {
            if (graph1[i, z] == 1 && !visited[z])   // check for visit
            {
                visited[z] = true;                  // mark as visited
                Console.Write(graph1VertexList[z]);
            }
        }
    }
}
...