problem in 8puzzle programm

Hi everyone,

I am working on 8 puzzle problem. tell me is there any error in this code. when i run this code for some input then after few seconds it stop working and debugging window open. here is my code....

#include <iostream>
#include <fstream>
using namespace std;

bool isOrdered( int **, int );
void puzzle( int **, int, int, int );
void swap( int **, int, int, int, int );

int main()
{
ifstream fin;
fin.open("puzzle.txt");
if( !fin.fail() )
{
int order = 0;
fin>>order;
int r = 0, c = 0;
int ** ptr = new int*[order];
for( int i = 0; i < order; i++ )
ptr[i] = new int[order];

for( int i = 0; i < order; i++ )
{
for( int j = 0; j < order; j++ )
{
fin>>ptr[i][j];
if( ptr[i][j] == 0 )
{
r = i; c = j;
}
}
}
puzzle( ptr, r, c, order);
}
}

void puzzle( int ** ptr, int r, int c, int order )
{
if( isOrdered( ptr, order ) )
return;

if( (r+1 >= 0 && r+1 < order ) && ( c>= 0 && c < order ) )
{
swap( ptr, r, c, r+1, c);
return puzzle( ptr, r+1, c, order );
}

if( ( r-1 >= 0 && r-1 < order ) && ( c>= 0 && c < order ) )
{
swap( ptr, r, c, r-1, c);
return puzzle( ptr, r-1, c, order );
}

if( ( r >= 0 && r < order ) && ( c+1 >= 0 && c+1 < order ) )
{
swap( ptr, r, c, r, c+1);
return puzzle( ptr, r, c+1, order );
}

if( ( r >= 0 && r < order ) && ( c-1 >= 0 && c-1 < order ) )
{
swap( ptr, r, c, r, c-1);
return puzzle( ptr, r, c-1, order );
}
}

bool isOrdered( int ** ptr, int order )
{
int min = ptr[0][0];
for( int i =0; i < order; i++ )
{
for( int j = 0 ; j < order; j++ )
{
cout<<ptr[i][j];
if( ptr[i][j] < min )
return false;
min = ptr[i][j];
}
}
return true;
}

void swap( int ** ptr, int r, int c, int r1, int c1 )
{
int temp = ptr[r][c];
ptr[r][c] = ptr[r1][c1];
ptr[r1][c1] = temp;
}
What does the debugging window tell you.
your program stop working correctly

For a start, you have a memory leak, you allocate a 2D array in your main() function and don't release the memory on exit - that wont be your problem but you should always release allocated memory when your finished with it.

What exactly is in puzzle.txt?

thanks for reply @softrix

memory leakage should be exist st the end. but the problem occurs within the puzzle() function.

this is the content of puzzle.txt
3 1 2 4 5 6 0 8 7 3
int order = 0;
fin>>order;
int r = 0, c = 0;
int ** ptr = new int*[order];

streamed input with a fixed buffer?
I didn't see fin.fail() or fin.good() anywhere.
Also when using fixed buffer size input, the last trailing data from a file will not be ending the size of your buffer unless you are 1 out of buffSize lucky.

Personally I (almost) never use formatted input so, I could be messed up on this with >>.
The docs say all basic streamed input uses the sentry for eof.
http://www.cplusplus.com/reference/istream/istream/operator>>/

That's what reading is good for if you get my meaning.
it's fin.fail() in fourth line of main function. and no problem with formatted input
Topic archived. No new replies allowed.