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;
}
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.
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.