Every problem in computer science, except for one, can be solved by adding more abstraction.
Start by writing the width traversal in the most abstract way:
void BreadthFirstTraversal(Graph graph, Vertex start) { }
We have a method that does what we want. Except that it is not written yet. So write it with a slightly less abstraction:
void BreadthFirstTraversal(Graph graph, Vertex start) { }
Continue by removing more and more abstraction.
void BreadthFirstTraversal(Graph graph, Vertex start) { var queue = new VertexQueue(); var markSet = new VertexMarkSet(); queue.Enqueue(start); markSet.Add(start); while(queue.NotEmpty()) { var vertex = queue.Dequeue(); foreach(Vertex neighbour in graph.ListNeighbours(vertex)) { if (!markSet.Contains(neighbour)) { markSet.Add(neighbour); queue.Enqueue(neighbour); } } } }
OK, now you have an algorithm that will work for any chart, regardless of its internal representation. So all you have to do is write ListNeighbours(Vertex) and you're done. (Assuming you already know how to write a queue and a set, or are ready to use types that are part of the base class library.) How are you going to do this?
Do you see how I used abstraction there? I really don't care if his adjacency matrix or adjacency list, all I care about is that the graph provides me with the service of giving me the neighbors of the vertex.
So, how are you going to write ListNeighbours(Vertex) based on your adjacency matrix?
Two possible solutions for research:
UPDATE: OK, so how can we make a sequence of neighbors outside the adjacency matrix?
Suppose each vertex is numbered, so Vertex really int ; this is traditionally done with adjacent matrices. We want to take to the vertex - int - and return a sequence of vertices that are its neighbors.
We have an array with the property that array[i, j] is nonzero if vertex j is a neighbor of vertex i .
Start the essay again and make your way to implementation:
public List<int> ListNeighbours(int vertex) { }
What do we need to do to accomplish this miracle?
public List<int> ListNeighbours(int vertex) { }
Alternatively, you can use yield return to create a sequence:
public IEnumerable<int> ListNeighbours(int vertex) { }
yield return Iterators tend to be simpler, but novice programmers often have difficulty challenging the control flow. Try writing it in both directions and see how it happens.