472,338 Members | 1,669 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,338 software developers and data experts.

Recursive algoritme for finding the shortest path

Hi!

I running my first year as industrial engineer (informatics)

We have an assignment to do :
.... create a playfield (matrix[DIM][DIM]). Some places in that field are
blocked, so you can't pass them. The others are free to go over ...

(I already found that part)
-> http://users.pandora.be/hebbrecht/jochen/c++/test.cpp

Now I need the find an algoritme to find the shortest way between to random
points in that field. I have a a lot possibilities ... But some are blocked
(because you can't pass them) ... Some are way too long!

This should be the algoritme:

for the four possibilities (east, south, west, north) {
if step is possible {// when you don't leave the playfield
make new point // execute step
distance = distance_from_next_point +1
if distance is'n't know in the new point OR distance is
smaller then distance {
remember distrance for new point
make step from new point
}
}
}

This is Pseudo code ... But I can't find the code in C++. It should be a
recursive one ... Who can help me out :-(?
Jul 22 '05 #1
20 16805

Webdad wrote:
Hi!

I running my first year as industrial engineer (informatics)

We have an assignment to do :
... create a playfield (matrix[DIM][DIM]). Some places in that field are blocked, so you can't pass them. The others are free to go over ...

(I already found that part)
-> http://users.pandora.be/hebbrecht/jochen/c++/test.cpp
Well, you probably need to have a word with your tutor about the
quality of his C++ course. You shouldn't be dealing with arrays.
Now I need the find an algoritme to find the shortest way between to random points in that field. I have a a lot possibilities ... But some are blocked (because you can't pass them) ... Some are way too long!

This should be the algoritme:

for the four possibilities (east, south, west, north) {
if step is possible {// when you don't leave the playfield
make new point // execute step
distance = distance_from_next_point +1
if distance is'n't know in the new point OR distance is smaller then distance {
remember distrance for new point
make step from new point
}
}
}

Sounds like the Dijkstra algorithm, special case with all distances are
+1.
www.boost.org has the graph library, which contains this algorithm:
http://www.boost.org/libs/graph/doc/...ry_review.html
Sounds like you can use Breadth-First Search.

Of course, using boost::graph may be somewhat harder than coding it
yourself, for such a simple case.

Regards,
Michiel Salters

Jul 22 '05 #2
Webdad wrote:
Hi!

I running my first year as industrial engineer (informatics)

We have an assignment to do :
... create a playfield (matrix[DIM][DIM]). Some places in that field are blocked, so you can't pass them. The others are free to go over ...

(I already found that part)
-> http://users.pandora.be/hebbrecht/jochen/c++/test.cpp
Well, you probably need to have a word with your tutor about the
quality of his C++ course. You shouldn't be dealing with arrays.
Now I need the find an algoritme to find the shortest way between to random points in that field. I have a a lot possibilities ... But some are blocked (because you can't pass them) ... Some are way too long!

This should be the algoritme:

for the four possibilities (east, south, west, north) {
if step is possible {// when you don't leave the playfield
make new point // execute step
distance = distance_from_next_point +1
if distance is'n't know in the new point OR distance is smaller then distance {
remember distrance for new point
make step from new point
}
}
}

Sounds like the Dijkstra algorithm, special case with all distances are
+1.
www.boost.org has the graph library, which contains this algorithm:
http://www.boost.org/libs/graph/doc/...ry_review.html
Sounds like you can use Breadth-First Search.

Of course, using boost::graph may be somewhat harder than coding it
yourself, for such a simple case.

Regards,
Michiel Salters

Jul 22 '05 #3

"msalters" schreef:
www.boost.org has the graph library, which contains this algorithm:
http://www.boost.org/libs/graph/doc/...ry_review.html
Sounds like you can use Breadth-First Search.

Of course, using boost::graph may be somewhat harder than coding it
yourself, for such a simple case.


Hmm, I looked the site very closefully ... But it's rather hard to
understand for a newbie as me ...
Maybe arrays aren't so good, but what would you take in mind?
Jul 22 '05 #4

"Webdad" <No**********@pandora.be> schrieb im Newsbeitrag
news:0H********************@phobos.telenet-ops.be...
Hi!

I running my first year as industrial engineer (informatics)

We have an assignment to do :
... create a playfield (matrix[DIM][DIM]). Some places in that field
are
blocked, so you can't pass them. The others are free to go over ...

(I already found that part)
-> http://users.pandora.be/hebbrecht/jochen/c++/test.cpp

Now I need the find an algoritme to find the shortest way between to
random
points in that field. I have a a lot possibilities ... But some are
blocked
(because you can't pass them) ... Some are way too long!

This should be the algoritme:

for the four possibilities (east, south, west, north) {
if step is possible {// when you don't leave the playfield
make new point // execute step
distance = distance_from_next_point +1
if distance is'n't know in the new point OR distance
is
smaller then distance {
remember distrance for new point
make step from new point
}
}
}

This is Pseudo code ... But I can't find the code in C++. It should
be a
recursive one ... Who can help me out :-(?


Do _not_ do such algorithms recursively - it's gonna go stack overflow
in the last test before shipping the release version, believe me.

instead of:
void Fill(int x, int y)
{
if(data[x][y]) return;
data[x][y]=1;
Fill(x-1, y); Fill(x+1,y); Fill(x,y-1); Fill(x,y+1);
}

do this:

struct PIXEL
{
int x,y;
};

void Fill(int x, int y)
{
std::stack<PIXEL> pixels;
pixels.push(PIXEL(x,y));
while(pixels.size())
{
PIXEL px = pixels.top;
pixels.pop();
if(!data[px.x][px.y])
{
data[px.x][px.y]=1;
pixels.push(PIXEL(px.x-1, px.y));
pixels.push(PIXEL(px.x+1, px.y));
pixels.push(PIXEL(px.x, px.y-1));
pixels.push(PIXEL(px.x, px.y+1));
}
}
}

see what I mean? Use a dynamic stack instead of recurs(e)ion.

-Gernot


Jul 22 '05 #5
Webdad wrote:

Hi!

I running my first year as industrial engineer (informatics)

We have an assignment to do :
... create a playfield (matrix[DIM][DIM]). Some places in that field are
blocked, so you can't pass them. The others are free to go over ...

(I already found that part)
-> http://users.pandora.be/hebbrecht/jochen/c++/test.cpp

Now I need the find an algoritme to find the shortest way between to random
points in that field. I have a a lot possibilities ... But some are blocked
(because you can't pass them) ... Some are way too long!


Search the web for 'Lee algorithm'.
Once you understand it, it is easy to implement.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #6

"Gernot Frisch" schreef:
Do _not_ do such algorithms recursively - it's gonna go stack overflow
in the last test before shipping the release version, believe me.


Yes, I know ... But that is the thing we are learning. For large fields,
it's gonna go stack overflow. I'll ask my tutor to use YOUR solution, but
I'm afraid he will disagree and say I have to use his solution ...
Jul 22 '05 #7
"Jochus" schreef:
Yes, I know ... But that is the thing we are learning. For large fields,
it's gonna go stack overflow. I'll ask my tutor to use YOUR solution, but
I'm afraid he will disagree and say I have to use his solution ...


Btw, this is my account ... This noon, I was using my dad's account ...
Jul 22 '05 #8
Gernot Frisch wrote:
[snip]
instead of:
void Fill(int x, int y)
{
if(data[x][y]) return;
data[x][y]=1;
Fill(x-1, y); Fill(x+1,y); Fill(x,y-1); Fill(x,y+1);
}

do this:

struct PIXEL
{
int x,y;
};

void Fill(int x, int y)
{
std::stack<PIXEL> pixels;
pixels.push(PIXEL(x,y));
while(pixels.size())
{
PIXEL px = pixels.top;
pixels.pop();
if(!data[px.x][px.y])
{
data[px.x][px.y]=1;
pixels.push(PIXEL(px.x-1, px.y));
pixels.push(PIXEL(px.x+1, px.y));
pixels.push(PIXEL(px.x, px.y-1));
pixels.push(PIXEL(px.x, px.y+1));
}
}
}

see what I mean? Use a dynamic stack instead of recurs(e)ion.


Use a different algorithm
The above is not even close to what the OP is lookin for.
--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #9
msalters wrote:
Sounds like the Dijkstra algorithm, special case with all
distances are +1.


I thought it looked like a weird Depth-First Search that relaxes edges.
Off hand, I have no idea whether such a thing would work or not.
Whatever it is, it's apparently recursive, yet finds shortest paths.

In any case, there is not much luck of the original poster finding
source code that does this online, if he is stuck using this bizarre
algorithm. The first place to start would be to find out the name of
the algorithm, if it has a name.

--
Dave O'Hearn

Jul 22 '05 #10
msalters wrote:
Sounds like the Dijkstra algorithm, special case with all
distances are +1.


I thought it looked like a weird Depth-First Search that relaxes edges.
Off hand, I have no idea whether such a thing would work or not.
Whatever it is, it's apparently recursive, yet finds shortest paths.

In any case, there is not much luck of the original poster finding
source code that does this online, if he is stuck using this bizarre
algorithm. The first place to start would be to find out the name of
the algorithm, if it has a name.

--
Dave O'Hearn

Jul 22 '05 #11
msalters wrote:
Sounds like the Dijkstra algorithm, special case with all
distances are +1.


I thought it looked like a weird Depth-First Search that relaxes edges.
Off hand, I have no idea whether such a thing would work or not.
Whatever it is, it apparently uses a stack (recursion) to find shortest
paths.

In any case, there is not much luck of the original poster finding
useful resources, if he is stuck using this bizarre algorithm. The
first place to start would be to find out the name of the algorithm, if
it has a name.

--
Dave O'Hearn

Jul 22 '05 #12
Jochus wrote:

"Gernot Frisch" schreef:
Do _not_ do such algorithms recursively - it's gonna go stack overflow
in the last test before shipping the release version, believe me.


Yes, I know ... But that is the thing we are learning. For large fields,
it's gonna go stack overflow. I'll ask my tutor to use YOUR solution, but
I'm afraid he will disagree and say I have to use his solution ...


So what *is* his solution.

The recursion is quite easy to do. Let us forget for the *shortest*
path for the moment. Just concenrate on *a* path.
BTW: The whole concept is called backtracking. I usually gave my
students a variation of your assignment, called: "How the mouse gets
the cheese": There is a labyrinth in a 2D array. Each array element
is marked as beeing either:
* empty space (' ')
* a wall ('*')
* the mouse ('M')
* the cheese ('C')
The goal is to find (using backtracking) a path from the mouse to
the chesse. As said: If you know backtrakcking this is quite simple
to do. Once that part runs, it is easy to generalize it such that the
shortest path can be found.
I will use that assignment in the discussion, since I don't want to do
your homework.

As most of the time with recursion you first have to think of a few
things. First you need to a global understanding of what your function
has to do:
Given a coordinate in the array (2 indices), find a way from that position
to the goal.

Plain and simple.

Next you should think about the trivial case. That is: When is this problem
so easy, that a solution can be given immediatly?
In the above example, the answer is (don't laugh it really is that trivial),
"When the coordinates already hold the cheese." In this case you found a
solution.

Are there any other trivial cases?
Yes, sure. When there is a wall at the position in question. Obviously the cheese
cannot be at this position. In this case case the search failed (for that position).

And in the other - non trivial - cases: Well, just try if the position to the north
leads to the chesse. If it does, fine you found a solution. The position in question
is part of that solution. If it does not, try to the south. If solution ....
If not, try west .... If not try east.

And that's it, for just one small detail: The mouse needs to keep track of what
positions it already tried, such that it will never try the same position again.
How is that done: Simple: just mark the array element with some character, lets
say a '.'. So we have one more trivial case: When the searched position contains
a '.' the search failed for that position, because the mouse had visited that
position already.

So your function will be

bool Search( int IndX, int IndY )

That is: search the maze at position IndX/IndY for the cheese.
The return value will either be true or false, depending if the
cheese was found or not.

Now filling in what we already know from the above:

bool Search( int IndX, int IndY )
{
// Trivial case 1:
// if that position contains the cheese: hurra

if( Maze[IndY][IndX] == 'C' ) {
cout << "Hurra: Found the cheese at " << IndX << " " << IndY << "\n";
return true;
}

// Trivial case 2:
// if that position contains a wall: sniff, the cheese cannot be here
if( Maze[IndY][IndX] == '*' )
return false;
// Trivial case 3:
// Position already visited: There is no sense in testing again. Cheese not found
if( Maze[IndY][IndX] == '.' )
return false;

// The mouse entered empty space, try north south, east, west
// If one of those searches leads to the chesse: fine
//
// But first mark that the mouse entered this field already:
Maze[IndY][IndX] = '.';

if( Search( IndX, IndY + 1 ) ||
Search( IndX, IndY - 1 ) ||
Search( IndX - 1, IndY ) ||
Search( IndX + 1, IndY ) ) {
cout << "Path " << IndX << " " << IndY << endl;
return true;
}

// sniff: The cheese is not at position IndX/IndY and a search
// to the north/south/east/west didn't come up with the cheese
// report failure to caller

return false;
}

and that's it.

A quick test program reveals:

#include <iostream>
using namespace std;

char Maze[7][16] = { "***************",
"* C * *",
"****** * *** **",
"* * * **",
"* ****** * ** *",
"* * * *",
"***************" };

bool Search( int IndX, int IndY )
{
.... See above
}

int main()
{

if( Search( 11, 3 ) )
cout << "Cheese found" << endl;
else
cout << "Cheese not found" << endl;
}

Step it through with your debugger until you clearly
understand how everything works. It might also be a
good idea to insert additional output statements
into Search: eg.

bool Search( int IndX, int IndY )
{
cout << "Testing position " << IndX << " " << IndY << "\n";

// Trivial case 1:
// if that position contains the cheese: hurra

if( Maze[IndY][IndX] == 'C' ) {
cout << "Hurra: Found the cheese at " << IndX << " " << IndY << "\n";
return true;
}

// Trivial case 2:
// if that position contains a wall: sniff, the cheese cannot be here
if( Maze[IndY][IndX] == '*' ) {
cout << "Hit a wall!\n";
return false;
}

....

Another hint: In your first attempts to follow the program flow in your
debugger, make sure the mouse starts near the cheese! Eg. a position
4 1 would be a good candiate.
Once you understand, how the mouse gets to the cheese, apply what you
have learned to your real problem. But: First make your program search
any path, then concentrate on letting it search for the shortest path!
--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #13
Karl Heinz Buchegger wrote:


Oh and by the way:
Look up 'backtracking'.
It is a mighty concept of beeing lazy: Test if
the goal is reached, if yes - fine, if not recurse
and try a variation. In fact the whole 'backtracking'
concept is nothing more then a clever ordered search
strategy through the whole solution space.

There are lots of other classical assignments for
backtracking: 8-queens, knapsack, stable marriage, ....

And yes, I expect every serious programmer to be able
to apply backtracking.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #14
"Karl Heinz Buchegger" schreef:
So what *is* his solution.

The recursion is quite easy to do. Let us forget for the *shortest*
path for the moment. Just concenrate on *a* path.
BTW: The whole concept is called backtracking. I usually gave my
students a variation of your assignment, called: "How the mouse gets
the cheese": There is a labyrinth in a 2D array. Each array element
is marked as beeing either:
* empty space (' ')
* a wall ('*')
* the mouse ('M')
* the cheese ('C')
The goal is to find (using backtracking) a path from the mouse to
the chesse. As said: If you know backtrakcking this is quite simple
to do. Once that part runs, it is easy to generalize it such that the
shortest path can be found.
I will use that assignment in the discussion, since I don't want to do
your homework. 8 SNIP 8<


Wow, thnx for all that typework! I read it and it soo much better to
understand ... But my teacher wants it to do like this:

for the four possibilities (east, south, west, north) {
if step is possible {// when you don't leave the playfield
make new point // execute step
distance = distance_from_next_point +1
if distance is'n't know in the new point OR distance is
smaller then distance {
remember distrance for new point
make step from new point
}
}
}

It must hold something like this ... But it's hard to program :-( ... As I
don't understand what this function would do....
Jul 22 '05 #15
Jochus wrote:

"Karl Heinz Buchegger" schreef:
So what *is* his solution.

The recursion is quite easy to do. Let us forget for the *shortest*
path for the moment. Just concenrate on *a* path.
BTW: The whole concept is called backtracking. I usually gave my
students a variation of your assignment, called: "How the mouse gets
the cheese": There is a labyrinth in a 2D array. Each array element
is marked as beeing either:
* empty space (' ')
* a wall ('*')
* the mouse ('M')
* the cheese ('C')
The goal is to find (using backtracking) a path from the mouse to
the chesse. As said: If you know backtrakcking this is quite simple
to do. Once that part runs, it is easy to generalize it such that the
shortest path can be found.
I will use that assignment in the discussion, since I don't want to do
your homework.

8 SNIP 8<


Wow, thnx for all that typework! I read it and it soo much better to
understand ... But my teacher wants it to do like this:

for the four possibilities (east, south, west, north) {
if step is possible {// when you don't leave the playfield
make new point // execute step
distance = distance_from_next_point +1
if distance is'n't know in the new point OR distance is
smaller then distance {
remember distrance for new point
make step from new point
}
}
}

It must hold something like this ... But it's hard to program :-( ... As I
don't understand what this function would do....


Study what I posted. Test it, run it, until you finally understand how
it works. (It is really the same concept). Then apply what you
have learned to your problem.

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #16
"Karl Heinz Buchegger" schreef:
Study what I posted. Test it, run it, until you finally understand how
it works. (It is really the same concept). Then apply what you
have learned to your problem.


Hmm, yes ... But am I wrong when I say that your solution isn't a
utilization on recursive methodes?

That's what this assignment holds on! Recursive functions ... Like
calculating faculties ... or "The Towers of Hanoi".
Jul 22 '05 #17
> Use a different algorithm
The above is not even close to what the OP is lookin for.


I just wanted to explain how to replace recursion - using a very
simple example.
BTW. Your cheese-mouse example was nice.
-Gernot
Jul 22 '05 #18
"Gernot Frisch" schreef:
I just wanted to explain how to replace recursion - using a very
simple example.


I spoke to my teacher: we MUST use recursion ... He agrees it isn't the best
solution, but it's good to learn us recursion...

The idea of mouse & cheese: he doesn't agree because it's an example on
backtracing ... I can't use that example ...
Jul 22 '05 #19
Jochus wrote:

"Karl Heinz Buchegger" schreef:
Study what I posted. Test it, run it, until you finally understand how
it works. (It is really the same concept). Then apply what you
have learned to your problem.


Hmm, yes ... But am I wrong when I say that your solution isn't a
utilization on recursive methodes?

That's what this assignment holds on! Recursive functions ... Like
calculating faculties ... or "The Towers of Hanoi".


Study it. The function is only 17 lines long (excluding comments).
There are *4* recursive calls!

--
Karl Heinz Buchegger
kb******@gascad.at
Jul 22 '05 #20

"Karl Heinz Buchegger" schreef:
Study it. The function is only 17 lines long (excluding comments).
There are *4* recursive calls!


This is the solution (well, allmost ...)

----

#include <iostream>

#include <ctime>

#include <cstdlib>

#include <iomanip>

//#define DEBUG

using namespace std;

const int DIM=10;

const int EIND=0;

const int MUUR=-1;

const int WEG=-2;

const int PAD=-3;

const int MIN=10;

const int MAX=60;

const int delta[4][2]= { {-1,0 } , {1,0} , {0,-1 } , {0,1} };

int lees_aantal_doolhoven() {

int run;

cin >> run;

while ( run < 0)

cin >> run;

return run;

}

void inlezen_speelveld (int matrix[][DIM], int dimensie, int &beginx, int
&beginy) {

for (int r=0; r < dimensie; r++) {

for (int k=0; k < dimensie; k++) {

cin >> matrix[r][k];

if ( matrix[r][k] == 0) {

beginx=r;

beginy=k;

}

}

}

}
bool binnen_veld (int xx, int yy, int dimensie) {

bool controle=false;

if (xx >= 0 && xx < dimensie && yy >= 0 && yy < dimensie)

controle=true;

return controle;

}

void kort(int matrix[][DIM], int dimensie, int x, int y) {

for (int i = 0; i < 4; i ++) {

int xx = x + delta[i][0];

int yy = y + delta[i][1];

if ( binnen_veld(xx,yy,dimensie) ) {

int t = matrix[x][y] + 1;

if (matrix[xx][yy] == -2 || (matrix[xx][yy] > 0
|| matrix[xx][yy] < matrix[x][y])) {

matrix[xx][yy] = t;

kort(matrix,dimensie, xx,
yy);

}

}

}

}

void uitschrijven(int matrix[][DIM], int dimensie) {

for (int r=0; r < dimensie; r++) {

for (int k=0; k < dimensie; k++)

cout << setw(3) << matrix[r][k];

cout << endl;

}

cout << endl;

}
int main () {

int run=lees_aantal_doolhoven();

cout << run << endl;

srand(time(NULL));
for (int i=0; i < run; i++) {

// dimensie is?

int dimensie;

cin >> dimensie;

cout << "dim:" << dimensie << endl;

// inlezen speelveld;

int matrix[DIM][DIM];

int beginx, beginy;

inlezen_speelveld(matrix,dimensie,beginx,beginy);
// kortste weg?

kort(matrix,dimensie,beginx,beginy);

// uitschrijven afstandenmatrix

uitschrijven(matrix,dimensie);

}

return 0;

}
Jul 22 '05 #21

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Porthos | last post by:
Hi All, I'm trying to find the minimum value of a set of data (see below). I want to compare the lengths of these attribute values and display...
6
by: Lau | last post by:
How do I easily calculate the shortest path between two geographical spots on a map? The map is divided into zones. So I guess it is possible to...
6
by: ThanhVu Nguyen | last post by:
Hi all, I need recommendation for a very fast shortest path algorithm. The edges are all directed, positive weights. Dijkstra shortest path...
4
by: Elmo Watson | last post by:
Is there a way, with the System.IO class, to do a recursive list of a directory structure? For instance, in DirectoryInfo, you have...
5
by: leezard | last post by:
I am developing a program using VB.NET that will accept a start and end point, the system then will generate the shortest path to reach the end...
5
by: costantinos | last post by:
Hello. I have implemented the Dijkstra shortest path algorithm, it works fine but I have one question on how I can improve something. I want to...
2
by: Bytter | last post by:
Hi everyone, I need to implement a very quick (performance-wise) Dijkstra shortest path in python, and found that libboost already has such...
5
by: aleya | last post by:
I am developing a program using VB.NET that will accept a start and end location (2 list boxes), the system then will generate the shortest path to...
9
by: pereges | last post by:
Hello I need some ideas for designing a recursive function for my ray tracing program. The idea behind ray tracing is to follow the...
0
by: concettolabs | last post by:
In today's business world, businesses are increasingly turning to PowerApps to develop custom business applications. PowerApps is a powerful tool...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: Naresh1 | last post by:
What is WebLogic Admin Training? WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge...
0
jalbright99669
by: jalbright99669 | last post by:
Am having a bit of a time with URL Rewrite. I need to incorporate http to https redirect with a reverse proxy. I have the URL Rewrite rules made...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.