maze solver in C++ [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have made a maze generator using Depth First Search which returns an array of pounds and spaces to indicate a maze. Example:
char maze[height][width] =
{
"#########",
"# # #",
"# ### # #",
"# # # #",
"# # # ###",
"# # # #",
"# ### # #",
"# # #",
"#########",
};
The agent will always start at the top left corner (maze[1][1]) and exit at the bottom right corner (maze[7][7]).
I am trying to make the solver now using Depth First Search.
The problem is I am quite a beginner to intermediate programmer so I am having a hard time understanding how to implement the Depth First Search in C++ and I'm having an even harder time implementing it for the maze.
I have a basic knowledge of stacks, queues etc. I also know how DFS works in a tree (pretty much in theory) but my main problem is how I would go to implement this in a maze which is stored in a 2D array.
I want to learn specifically DFS so I can get started and then I'll implement other search tactics (like BFS for example) to start getting a hand on AI.
EDIT: I don't want ready code!!! I want you to help me understand how to transfer pseudocode to C++ for a maze!

So the basic operation of a depth first search is:
This works the same for any arbitrary graph as for a tree. A tree is just a special case. You can even visualize your maze as a tree:
#########
#123# #
#4### # #
#5# # #
# # # ###
# # # #
# ### # #
# # #
#########
The only difference between using this algorithm on a tree vs. an arbitrary graph is that it's implicitly known which nodes in a tree have been visited, due to the hierarchical structure of a tree. With an arbitrary graph you might have a structure like:
#####
#187#
#2#6#
#345#
#####
And when examining node eight you don't want to treat node one as a new place to visit.
With your maze one way to remember which nodes have been visited would be to fill them in with '#' as soon as you encounter them.
I have pretty much figured out how to represent the position of the agent, how to move him around and such but my problem mostly is in how to use the stack for keeping track of which places the agent has been. By what I've found in google some keep a stack of the visited places but I never really understood when to remove positions from the stack, that's my biggest confusion
The stack itself is not used to keep track of which places are visited. It only keeps track of the current 'path' taken through the maze. When you reach a dead end nodes get removed from the stack; Those nodes must remain marked as visited even though they are removed from the stack. If removing those nodes also causes those nodes to be 'unvisited' then your search may continually try and retry dead ends.
I recommend that you first draw out a few little mazes and walk through them by hand using the flow chart above. This will give you a better understanding of the algorithm. Here are some example mazes:
Start at O, finish at X
#### ##### ##### #####
#OX# #O X# #O#X# #O #
#### ##### ##### # #X#
#####
Then consider each box in the flow chart and think about what data it uses, how to represent that data, and how to implement the box's action in code using that data.

Related

How can I properly list items in xaringan slide without misaligned dots?

I often encounter the misaligned dots whenever I list the items in xaringan slides for some reason. I think I ensure that there's no extra or unnecessary space between the codes or items. I just want to know what kind of mistakes I usually make in this case. FYI, there is only a single space between # Consistency and #### and #### is for larger fontsize. I know - is a simple way to list but this size is sometimes smaller for my need.
---
# Consistency
#### </li> How does an estimator perform? <li>

L-System tree won't branch correctly

I have tried to implement the L-System in c++ with SFML, but for some reason it doesn't work as expected.
I tried replicating this program:
https://www.youtube.com/watch?v=E1B4UoSQMFw?t=1256
And everything works fine except the branching. At the timestamp(20:56) you can see the tree branching off into two branches, and these two branches branch off individually.
However, this shouldn't be possible due to the rules(the turtle can save position/rotation to make a new branch, but it can only save one position at a time so branching off inside a branch multiple times isn't possible)
In my program instead of branching off in two branches that are branching off individually only one of the branches(right one) branches of further, as should be expected.
But why then does his code produce a completely different result, that shouldn't be possible with this ruleset?
You implemented an L system with the following alphabet:
Alphabet: F+-[]
And the following rule:
Rule 1: F → FF+[+F-F-F]-[-F+F+F]
The meanings of the alphabet characters are very turtle-graphic-like and are as follows:
F Move forward 1 unit and draw a line as you go.
+ Turn Clockwise
- Turn Counter-Clockwise
[ Push the current state onto the stack.
] Pop state from the stack and make it the current state.
This requires that you know what a stack is.
You can see, because there is an F inside the square brackets in the rule, how in the second generation there will be nested square brackets.
(Sorry for the long line below, but it's a long rule and breaking the line would be confusing. Just scroll right. Observe how I have highlighted the outer group of matching nested brackets.)
FF+[+F-F-F]-[-F+F+F]FF+[+F-F-F]-[-F+F+F]+[+FF+[+F-F-F]-[-F+F+F]-FF+[+F-F-F]-[-F+F+F]-FF+[+F-F-F]-[-F+F+F]]-[-FF+[+F-F-F]-[-F+F+F]+FF+[+F-F-F]-[-F+F+F]+FF+[+F-F-F]-[-F+F+F]]
[...............................................................] [...............................................................]
When applying the turtle-graphics interpretation, when we encounter a second [ before encountering a ], we will now have multiple states saved on the stack. An arbitrary number of states may be saved. The stack is "first in, last out", much like stacking plates, you can only access the plate at the top of the stack. Each time you push state with [ it's like adding a plate to the stack of plates. When you see a ] you remove the top plate from the stack. To remove a plate from the top of the stack in this way is to pop it. Each plate, in this scenario, represents the state of the turtle as it was when it was pushed. Popping a state restores the turtle's position and orientation back to that saved position.

Finding Shortest Distance on Graph -- Logic Issue

In my C++ course we have been working on graphs for a while, and there's a certain question that I've been stuck on for quite some time. The teacher gave us a program that created a graph of integers and then was able to find the shortest path between two integers in the graph. Our job was to adapt this to work for strings (specifically, find the shortest path only jumping to words that have 1 different letter than the previous word e.g bears -> beard).
Here is a sample of what I would expect my program to do:
Given the list [board, beard, bears, brand, boars, bland, blank]
it would create an edge matrix that resembled this:
board | beard boars
beard | board bears
bears | beard boars
brand | bland
boars | board bears
bland | brand blank
blank | bland
And then if asked to find the distance between board & bears it would output:
board->beard->bears
The way I adapted my program is that it creates a graph of a struct named 'node' which contains a number and a word. I use the number to compare the order within one vector to other variables, and the word to create the path. My adapted program successfully creates the graph from data in a text file and connects all words that have a 1 letter difference, however, when I run my function to find the shortest distance it bypasses my edges and simply print out that the start word and end word are a distance of 1 apart.
I will post my full, compile-able program below and explain what I know about the problem.
Here is a link to two pastebin links (I do not have a high enough reputation yet to post more than two links so I must combine them) The first is my full program, I have adapted it to use a set of words that I know are a word distance of 1 apart rather than a text file.
http://pastebin.com/W7HRZG2v
This second link is a download of the code my teacher gave (in case you wish to see a working version of the program)
I've narrowed the problem down to how I'm filling the vector "parents". Somehow it isn't generating properly and is creating an issue when the program tries to retrieve a path from it.
Here is a link to a photo (reputation not high enough to post images yet) comparing what the parents vector looks like in my teacher's "healthy" program (find distance between 2 & 5) to the parents vector in my program:
http://puu.sh/95zQI/26e9b83b9a.png
Notice how in my teacher's, 2 and 4, both integers used in the path, are present in the parents vector and called on to create it.
Notice how in mine the only word present in the parents vector is the beginning word, and hence it is the only word available to call on. However when comparing the way my teacher filled parents with the way I do, there are no differences I can see, aside from the fact that my parents is a string so I am entering a word instead of a number:
(my adapted version is on the left, teacher's is on the right)
if (distanceNodes[edgeNum] > distanceNodes[currNum] + 1) | if (distanceNodes[edge] > distanceNodes[curr] + 1)
{ | {
distanceNodes[edgeNum] = distanceNodes[currNum] + 1; | distanceNodes[edge] = distanceNodes[curr] + 1;
parents[edgeNum] = curr->word; | parents[edge] = curr;
} | }
If someone more proficient in graph application could look at this and assist me I would be extremely grateful. I've been stuck on this problem for over a week and the only tip my teacher will give me is that I should compare my program to his line by line; I did that and I still can't find the problem, I'm about ready to give up.
If you can help me, thank you very much,
Tristan
Here:
node * one = createNewNode(1, "board");
...
node * three = createNewNode(3, "bears");
...
insertEdge(&g, one, three);
The program correctly finds the edge you put there.
More generally, you must learn to step through your code and see what's happening.
And don't use global variables if you can help it.
EDIT:
I had some free time, so here's another problem:
int currNum = start->num;
while (! inTree[currNum])
{
...
parents[edgeNum] = curr->word;
...
}
You iterate by number, but you look things up by a pointer which you never update.
I'm sure there are other problems. The bottom line is that you're not checking things. For some reason, testing, which real coders do all the time, is never taught in programming courses.

Convert array to nodes

Let me start off with saying that I have very basic knowledge of nodes and graphs.
My goal is to make a solver for a maze which is stored as an array. I know exactly how to implement the algorithm for solving (I'm actually implementing a couple of them) but what my problem is, is that I am very confused on how to implement the nodes that the solver will use in each empty cell.
Here is an example array:
char maze[5][9] =
"#########",
"# # #",
"# ## ## #",
"# # #",
"#########"
My solver starts at the top left and the solution (exit) is at the bottom right.
I've read up on how nodes work and how graphs are implemented, so here is how I think I need to make this:
Starting point will become a node
Each node will have as property the column and the row number
Each node will also have as property the visited state
Visited state can be visited, visited and leads to dead end, not visited
Every time a node gets visited, every directly adjacent, empty and not visited cell becomes the visited node's child
Every visited node gets put on top of the solutionPath stack (and marked on the map as '*')
Every node that led to a dead end is removed from the stack (and marked on the map as '~')
Example of finished maze:
"#########",
"#*~#****#",
"#*##*##*#",
"#****~#*#",
"#########"
Basically my question is, am I doing something really stupid here with my way of thinking (since I am really inexperienced with nodes) and if it is could you please explain to me why? Also if possible provide me other websites to check which implement examples of graphs on real world applications so I can get a better grasp of it.
The answer really depends on what you find most important in the problem. If you're searching for efficiency and speed - you're adding way too many nodes. There's no need for so many.
The efficient method
Your solver only needs nodes at the start and end of the path, and at every possible corner on the map. Like this:
"#########",
"#oo#o o#",
"# ## ## #",
"#o oo#o#",
"#########"
There's no real need to test the other places on the map - you'll either HAVE TO walk thru them, or won't have need to even bother testing.
If it helps you - I got a template digraph class that I designed for simple graph representation. It's not very well written, but it's perfect for showing the possible solution.
#include <set>
#include <map>
template <class _nodeType, class _edgeType>
class digraph
{
public:
set<_nodeType> _nodes;
map<pair<unsigned int,unsigned int>,_edgeType> _edges;
};
I use this class to find a path in a tower defence game using the Dijkstra's algorithm. The representation should be sufficient for any other algorithm tho.
Nodes can be of any given type - you'll probably end up using pair<unsigned int, unsigned int>. The _edges connect two _nodes by their position in the set.
The easy to code method
On the other hand - if you're looking for an easy to implement method - you just need to treat every free space in the array as a possible node. And if that's what you're looking for - there's no need for designing a graph, because the array represents the problem in a perfect way.
You don't need dedicated classes to solve it this way.
bool myMap[9][5]; //the array containing the map info. 0 = impassable, 1 = passable
vector<pair<int,int>> route; //the way you need to go
pair<int,int> start = pair<int,int>(1,1); //The route starts at (1,1)
pair<int,int> end = pair<int,int>(7,3); //The road ends at (7,3)
route = findWay(myMap,start,end); //Finding the way with the algorithm you code
Where findWay has a prototype of vector<pair<int,int>> findWay(int[][] map, pair<int,int> begin, pair<int,int> end), and implements the algorithm you desire. Inside the function you'll probably need another two dimensional array of type bool, that indicates which places were tested.
When the algorithm finds a route, you usually have to read it in reverse, but I guess it depends on the algorithm.
In your particular example, myMap would contain:
bool myMap[9][5] = {0,0,0,0,0,0,0,0,0,
0,1,1,0,1,1,1,1,0,
0,1,0,0,1,0,0,1,0,
0,1,1,1,1,1,0,1,0,
0,0,0,0,0,0,0,0,0};
And findWay would return a vector containing (1,1),(1,2),(1,3),(2,3),(3,3),(4,3),(4,2),(4,1),(5,1),(6,1),(7,1),(7,2),(7,3)

Constructing a tree from an array for a DFS solver

I am making a maze solver using DFS and I want to implement the search tree for it but I am a bit new to artificial intelligence and I want a little bit of help on this matter.
Let me give a maze example first:
char maze[5][9] =
"#########",
"# # #",
"# ## # #",
"# # #",
"#########",
So my search tree for DFS should be something like this:
"#########",
"#12#15 10 11 #",
"#3##14 9 #12 #",
"#456 7 8 #13 #",
"#########",
1st child of parent -> Right Cell if it is empty
2nd child of parent -> Bottom Cell if it is empty
3rd child of parent -> Left Cell if it is empty
4th child of parent -> Top Cell if it is empty
My solver will receive as an argument my maze array. My questions are these:
1st question: Is this actually the way the nodes are going to get visited by my actor?
2nd question: In the code do I need to declare 15 as child of 10? (also in other cases like 9 with 14)
3rd question: When my solver receives the array do I need to make a pre-process on the array and construct the tree from the array or will my actor construct it as he goes?
I also assume the rule of "do not include a node in the solution tree if it was already in the tree"? Because that sure helps.
Typically the tree is implicit, and you only construct the parts of the tree you actually visit, often tearing things down as you roll it back.
Your solver keeps track of the current steps along the tree. You probably also want to keep track of what cells you have explored in the maze. If the maze has only # and characters, use * to indicate you have visited the cell in this solver.
You start at some location. If that location is valid, you mark it with a * so you don't come back to it, and add that location (say, (1,1))to your "stack" of your path.
Now, you follow the rules you wrote above. Check the cell under your current location. Is it empty? (not a # or a *) If so, recurse, asking if that finds the way out.
If it finds the way out, take the path it found, prepend your current node, and return that path as the way out.
If it does not, search in the next adjacent cell (by the order above).
Finally, wrap the above recursive routine with a function that calls it, then removes the * marks from the map.
The tree you walk is implicitly coded. Building the tree forces you to visit every node, and you only want to build the parts that you have to.
This can be optimized in a number of ways. You can avoid writing to the map by working on a "ghost" copy of it. You can avoid prepending by passing the stack to the recursive versions, which carefully remove any extra nodes if they fail, and leave them on if they succeed. Or you can use a real stack, and encode the path backwards, with a wrapping function that (after all the work is done) reverses the path so it is in a more conventional order.