Depth first search - 2D Game map

后端 未结 1 955
北恋
北恋 2020-12-20 15:12

I have created a 2D maze, and I want to find the quickest path between the red->blue colored nodes. I\'m an unsure how I would go about implementing a depth-first search. I

相关标签:
1条回答
  • 2020-12-20 15:56

    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.

    0 讨论(0)
提交回复
热议问题