Depth first traversal of Java graph to randomly generate maze

Recently, I often watch my classmates playing a maze game in the computer room. It's more interesting. I also write an algorithm for randomly generating mazes in Java. In fact, it is a depth first traversal algorithm of graphs The basic idea is that every point in the maze has four walls, and then what.

1. Access from any point (fixed in my algorithm is from point (0,0)), access to a random one in four directions (remove the wall in that direction of the point every time an accessible point is accessed), and the accessed point continues to access downward in this way. 2. Each accessed point is marked as accessed. When a point accesses a certain direction, we will first judge whether the accessed point has been accessed or touches the boundary If the point is accessed or inaccessible in all four directions, return to the previous point. The previous point continues the process.

After such a traversal, it can be determined that each point has been visited, and because the direction of each visit is random, many different traversal situations will be formed. At the same time, the path between each two points is unique, which will form a different maze, and there is only a unique path from the starting point to the end point, which is determined by the characteristics of the depth traversal algorithm of the graph. In the implementation of the algorithm, we mainly use the stack. For the first time, we first press the first point into the stack. Every time we access a point, we press the point into the stack. Then we randomly access the point on the top of the stack in four directions, access the new point, and press the new point in. Once the point is inaccessible in four directions, let the point back off the stack, and then access the four directions of the point on the top of the stack, and so on, Until all the points in the stack exit, our traversal succeeds. This is a recursive process. Naturally, this algorithm can be implemented by recursive method. However, I do this here by manually using an array as the stack. Ha ha ~ ~ after saying so much, I don't know whether I want to express it or not. However, I feel that my specific code design is still not well written. There are still many places that lack perfection and optimization. The right should be algorithm practice. The following are the core codes of two key classes. As for the code of the presentation layer, it will not be posted because they are very trivial.

The following is the rendering:

Class of maze:

maze

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>