Depth first search - 2D Game map

瘦欲@ 提交于 2019-11-29 13:25:02

For 2D Maze you can simply use Breadth First Search instead of Depth First Search, It will find it in O(n2) if you have n*n maze.

But there is another option, which is kind of labeling and BFS and works on your maze (no need to graph).

Numbering algorithm

One of an interesting ways to understand the breadth first search is do it in this way (for maze):

  1. Set all cells to 0, and set blocks to -1

  2. Start from your source position set it to 1, mark all of it's 0 neighbors to 2, and save all 2's in a list. after that mark all 0 neighbors of 2's to 3, clear list of 2's and save list of 3's and go on to reach the destination. in each level just do not change the source value.

  3. Now assume you are in destination and you want to find path, your destination has score m, find neighbor with score m-1, .... and output the path.

In fact normal and simple way of BFS is using Q, but I offered this for it's simplicity and because it simulates Q manner.

Using adjacency matrix

For creating adjacency matrix, you should have named node and edges, so you can have a classes like below for edges and nodes (I wrote it in pseudo C#):

public class Edge
{

   public Edge(Node start, Node end, decimal weight)
   {
      StartNode = ...,...,...
   }
   public Node StartNode;
   public Node EndNode;
   public decimal weight;
   public bool IsDirected;
}

public class Node
{
   public Node(int index)
   {
        this.Index = index;
   }
   public int Index;
   public List<Edge> Edges = new List<Edge>();
   public bool Visited = false;
}

Now your graph is list of your Node objects:

public class Graph
{
   public List<Node> Nodes = new List<Node>();
}

And for modeling your Maze you should select cells as node, and draw edge between neighbor cells. I'll left it to you how to add node to your graph.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!