Depth first search for a graph in C - c

I made the whole adjacency list representaion of graphs. I was able to implement BFS code as well. However, I am not able to understand DFS.
I have been able to come up with this algorithm:
Mark the source vertex as visited.
Push it on stack.
While stack is not empty
{
remove the vertex and name it as v.
call dfs for all the neighbours of v.
}
Is this correct? I want to do a complete traversal of the graph. There should be a base case as well in this, but what will it be?

You need to keep a visited array to keep track of all nodes that you have visited before.
And then avoid visiting the same nodes again and again.
This way your program will definitely terminate successfully

Related

Can somebody please explain this pseudo code to me in terms of java code?

Here is the code for a BFS, I don't understand what this means in java code. terms like .pathlen, the arrows, etc I don't understand any of it. Can anyone clarify? thanks.
Image of the code
Iterate through each vertex of graph g and mark a boolean as not visited.
Initialize a queue of vertices.
Mark and declare the starting node as visited.
Set the length of the path to the starting node as 0. This would be an integer field variable in the vertex class.
Add the first node to the queue.
While the queue is not empty, repeat the following.
Remove the head node from the queue.
For every edge that is adjacent to the vertex you removed, so you would go through the adjacency list or matrix on the graph and look for edges close to it.
If the node's boolean variable says that the edge's destination is not visited, then:
Add the edge's destination to the queue.
Mark the destination node from the edge as visited.
Add one to the length of the path on the edge's node, on top of the starting node's edge weight.
Note: If you have a weighted graph then you can do something other than +1 on step #12. But you shouldn't terminate the BFS until it runs on all nodes if you make it weighted.
Pathlen is just a member variable. Think of that like the syntax for accessing a public variable of a java class.
The arrow syntax is a syntax for assignment, the equivalent of java's =. It means "Take the thing on the right and assign the thing on the left that value."

How can I count the number of valid squares in each group?

EDIT:I have a logical error and I don't know how to fix it.This is my code. I think that the problem is in the while function at line 245. It doesn't add the next valid pixel to the queue, so the queue becomes 0 and it exits the WHILE function.
I need help from a veteran here! I have something like a chess table, with equal sized squares, numbered from bottom to top, right to left, but only some of them are valid for me (as shown in the picture I posted a link to). I deleted the non-valid ones from the table.
I want my C program to count the squares in each group. As you can see in the image, a valid group only has directly connected squares, and squares that connect only diagonally are not in the same group. I used colors to evidentiate the valid groups in my picture.
I know the table's width and height and I know how many squares and valid squares it has.
I stored their numbers in a vector, but I can't figure out how to count the squares in each group.
How can I do this?
Here is my picture:
I want to find out a method which works for larger "chess tables", like pictures with known sizes.
What you surely miss is : What group a valid square belongs to ?
You could use graph theory to solve that.
But you can also try some other approach.
For instance, you can use one tag list which will keep track of already visited nodes or not. You can use a vector of vector for managing group nodes.
Browse the table with same direction let's say from top left to bottom right. Check only non visited nodes.
When a valid square is found which is non visited add this node to vector[count++] and flag this node to visited.
Look for this node connected squares in bottom right direction. If one is found then flag it to visited and add the node in the same vector[count] list.
You repeat the same process until you cannot find anymore connected components (with recursion for instance).
If no connected squares are found anymore in the same group continue step 1.
At the end just sum of each of your vector[count] and it should give the expected results (for performance you could do that on the fly while looking connected components).
You should categorize each connected squares into a single component and count the size of each component. For that you can use a nested data structure such as vector to store the connected squares and nest it inside a map to distinguish the other connected squares. like,
map<int squareIndex, vector<squares> >
The basic idea is to have a visited array so that you can ignore the already visited squares. The algorithm follows just like doing Breadth First Search in Graphs. You can use a Queue to store the adjacent connected components of the current square. I would suggest to do the following.
Algo
traverse through the array from 1 to N
If queue is empty then make new index in map and push element into your map
If visited[element] is true then go to step 1, else visited[element]=true and push element into your map.
element = dequeue()
enqueue adjacent squares of the current element and repeat from step 2 for the current element
In this way finally your map will be of size 4 (for the given case) and each map element will contain a vector of the connected squares. Use size property of each vector to count the number of squares in each index.
You are searching for something called connected component.
This post sheds some light on the subject but there's a number of different implementations available on the Web.

open maze - Depth First Search

I have an open maze with a start point and an endpoint. I wrote a BFS and a DFS search algorithm to solve the maze. My BFS finds the shortest solution, but my DFS (which goes down, left, up, right) creates a zigzag as a solution. Is this correct? How should DFS behave in an open maze?
edit:
http://postimg.org/image/n049oua8n/ here is the path, starting form P. The endpoint is on the bottom, but the mid-path looks wrong to me =/ I think the algorithm is skipping a column, right? it should fill the middle section completely?
Yes, it correct because DFS explores the graph in depth (and doesn't find the shortest paths). Given the source of a visit s, DFS visits one of its neighbors u, then one of u's neighbors going in depth. When all the neighbors of a given node are visited another neighbor of the parent node is visited, and so on.
While BFS, given the source of the visit s first visits all it's neighbors and then begins deepening.
That sounds correct: a DFS will go as deep in the maze as it can in the first direction (down), and when it can't get any further it will backtrack to the last crossroads and go left, and then down again.
There is a painting algorithm called "flood fill" which fills a space with color by making a DFS or BFS of the pixels. The animations of its working give a nice graphical representation of the differences between the two graph search algorithms.
This is a food fill with BFS, as you can see it searches the space in every direction:
This is a flood fill with DFS, as you can see it searches the space first in one direction, and then backtracks to fill holes:

Rush hour - Iterative Deepening

I have to solve the "rush hour puzzle" by iterative deepening algorithm. I have read a lot of topics here on stackoverflow and also on the internet. I think that I understand the iterative deepening algorithm. Basically you just go deeper into the tree and try to find the solution.
I figured that I need to create a graph or a tree from the puzzle, but I really don't have an idea how. Also, if I would have the tree, then how would I tell if something is a valid move or a final state?
There were answers that the nodes should be possible moves and the edges are between the nodes that can be reached in one move. I can imagine this, but somehow I'm getting trouble in see how this can be useful or better yet how can this solve the problem.
Please help me, I'm not asking for complete solution or code sample, I just need some easy explanation of the problem.
There is a reason you need to use the deepening algorithm. Imagine you name each car A, B, C, D... The root node of your tree is the initial board state. Now, move car A. You go down one node in the tree. Move car A back. You are at the initial state, but you made two moves to get here, so you are two nodes down the tree. Repeat over and over. You will never hit a final state.
The root node of your tree is the initial board state. Given that node, add a child node to it for every possible valid move. So, each child node will be what the initial tree looks like after one move. Now, for each of those child nodes, do the same thing: make a child node where each node is one move off the original child node.
Eventually, you will hit a solution to the puzzle. When that happens, you print the moves from the root node to the solution child node and quit. This algorithm ensures that you find a solution with the least number of moves.

Entering / Exiting a NavGraph - Pathfinding

I've got a manually created NavGraph in a 3D environment. I understand (and have implemented previously) an A* routine to find my way through the graph once you've 'got on the graph'.
What I'm interested in, is the most optimal way to get onto and 'off' the Graph.
Ex:
So the routine go's something like this:
Shoot a ray from the source to the destination, if theres nothing in the way, go ahead and just walk it.
if theres something in the way, we need to use the graph, so to get onto the graph, we need to find the closest visible node on the graph. (to do this, I previously sorted the graph based on the distance from the source, then fired rays from closet to furthest till i found one that didn't have an obstacle. )
Then run the standard A*...
Then 'exit' the graph, through the same method as we got on the graph (used to calculate the endpoint for the above A*) so I take and fire rays from the endpoint to the closest navgraph node.
so by the time this is all said and done, unless my navgraph is very dense, I've spent more time getting on/off the graph than I have calculating the path...
There has to be a better/faster way? (is there some kind of spacial subdivision trick?)
You could build a Quadtree of all the nodes, to quickly find the closest node from a given position.
It is very common to have a spatial subdivision of the world. Something like a quadtree or octree is common in 3D worlds, although you could overlay a grid too, or track arbitrary regions, etc. Basically it's a simple data-structures problem of giving yourself some sort of access to N navgraph nodes without needing an O(N) search to find where you are, and your choices tend to come down to some sort of tree or some sort of hash table.

Resources