Finding the shortest path in a grid with BFS

The Breadth-First Search (BFS) algorithm is another basic technique for graph traversal and it's aimed to get the shortest path in the fewest steps possible, with the trade-off being expensive in terms of memory; thus, aimed specially at games on high-end consoles and computers.

Getting ready

This is a high-level algorithm that relies on each graph's implementation of the general functions, so the algorithm is implemented in the Graph class.

How to do it...

Even though this recipe is only defining a function, please take into consideration the comments in the code to understand the indentation and code flow more effectively:

  1. Declare the GetPathBFS function:
    public List<Vertex> GetPathBFS(GameObject srcObj, GameObject dstObj)
    {
        if (srcObj == null || dstObj == null)
            return new List<Vertex>();
        // next steps
    }
  2. Declare and initialize the variables we need for the algorithm:
    Vertex[] neighbours;
    Queue<Vertex> q = new Queue<Vertex>();
    Vertex src = GetNearestVertex(srcObj.transform.position);
    Vertex dst = GetNearestVertex(dstObj.transform.position);
    Vertex v;
    int[] previous = new int[vertices.Count];
    for (int i = 0; i < previous.Length; i++)
        previous[i] = -1;
    previous[src.id] = src.id;
    q.Enqueue(src);
  3. Implement the BFS algorithm for finding a path:
    while (q.Count != 0)
    {
        v = q.Dequeue();
        if (ReferenceEquals(v, dst))
        {
            return BuildPath(src.id, v.id, ref previous);
        }
    
        neighbours = GetNeighbours(v);
        foreach (Vertex n in neighbours)
        {
            if (previous[n.id] != -1)
                continue;
            previous[n.id] = v.id;
            q.Enqueue(n);
        }
    }
    return new List<Vertex>();

How it works...

The BFS algorithm is similar to the DFS algorithm because it's based on the same in-order traversing of a graph but, instead of a stack such as DFS, BFS uses a queue for visiting the discovered nodes.

There is more…

In case you haven't noticed, we didn't implement the method BuildPath. This is because we talked about it at the end of the Depth-First Search recipe.

See also

  • Finding your way out of a maze with DFS, recipe.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.204.186