i have written the code . the while loop works good for right and down only. when i=9 and j=5 then it do not execute further . iam trying to fix the problem but not successful.
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
//----------------------------------------------------Print maze
void fnPrintMaze(int m,int n,int**a)
{
for (int i=0; i<=m-1; i++)
{
for (int j=0; j<=n-1; j++)
{
cout<<a[i][j];
cout<<" ";
}
cout<<endl;
}
}
//----------------------------------------------------Find Path
void fnFindPath(int m,int n, int **a)
{
int i=0;
int j=0;
if(i==0 && j==0)
a[i][j]=2;
do{
if((i>=0 && j+1>=0 && i<=m-1 && j+1<=n-1 )&& a[i][j+1]==0)//right
{j++;
a[i][j]=2;
}
else if((i+1>=0 && j>=0 && i+1<=m-1 && j<=n-1) && a[i+1][j]==0)//down
{i++;
a[i][j]=2;
}
else
if((i>=0 && j-1>=0 && i<=m-1 && j-1<=n-1) && a[i][j-1]==0) //left
{
j--;
a[i][j]=2;
}
else if((i-1>=0 && j>=0 && i-1<=m-1 && j<=n-1) && a[i-1][j]==0) //up
{
i--;
a[i][j]=2;
}
/*
else
if((i-1>=0 && j>=0 && i-1<=m-1 && j<=n-1) && a[i-1][j]==2) //revisit up
{
a[i][j]=3;
i--;
}
else if((i>=0 && j-1>=0 && i<=m-1 && j-1<=n-1) && a[i][j-1]==2) //revisit left
{
a[i][j]=3;
j--;
}
*/
else
//{
if((i>=0 && j+1>=0 && i<=m-1 &&j+1<=n-1) && a[i][j+1]==2)
{
a[i][j]=3;
j++;
}
else if((i+1>=0 && j>=0 && i+1<=m-1 &&j<=n-1) && a[i+1][j]==2)
{
a[i][j]=3;
i++;
}
else if((i>=0 && j-1>=0 && i<=m-1 && j-1<=n-1) && a[i][j-1]==2)
{
a[i][j]=3;
j--;
}
else if((i-1>=0 && j>=0 && i-1<=m-1 && j<=n-1) && a[i-1][j]==2)
{
a[i][j]=3;
i--;
}
//}
}while( ( i!=m-1) &&( j!=n-1));
//while( !( i==m-1 && j==n-1));
}
int main(int argc, char *argv[]) //main programe
{
int m, n;
int **maze;
fstream fin("maze.txt", ios::in);
fin>>m;
fin>>n;
maze= new int*[m]; //defining rows
for (int i=0; i<=m-1; i++)
maze[i]=new int[n]; //defining columns
for (int i=0; i<=m-1; i++) //reading values from txt and putting in matrix
for (int j=0; j<=n-1; j++)
fin>>maze[i][j];
fnPrintMaze(m,n,maze);
//for (int i=0; i<=m-1; i++)
// for (int j=0; j<=n-1; j++)
fnFindPath( m,n, maze);
cout<<endl;
fnPrintMaze(m,n,maze);
system("PAUSE");
return EXIT_SUCCESS;
}
the matrix is
10 10
0 1 1 1 0 0 0 0 0 0
0 0 0 1 0 0 0 1 0 0
0 1 0 1 1 0 0 1 0 0
0 1 0 0 1 0 1 1 0 0
0 1 0 0 1 0 1 1 0 0
1 1 1 0 1 0 1 0 0 0
0 0 1 0 0 0 1 0 1 1
0 0 1 0 0 0 1 0 1 1
0 1 1 0 1 0 1 0 0 0
0 0 0 0 1 0 1 1 0 0