I wrote the below code and it is showing me segmentation fault but when I run in any online compiler it is working fine. Can anyone please explain to me what is the reason for this strange behaviour ?
For added information, I'm running Linux Ubuntu with GCC compiler.
Moreover, i noticed that if I put a return statement after std::cin>>n
, then it doesn't show the error, but as soon as the input loop starts where I take the input for maze[i][j], it shows error. And I'm not going out of bound for the array, I am taking n as 5.
#include<iostream>
#define ll long long int
bool safe(ll x, ll y, ll n, ll value)
{
if(x>=0 and x<n and y>=0 and y<n and value==1)
return true;
return false;
}
bool solve_maze(ll maze[1005][1005], ll sol[1005][1005], ll n, ll x , ll y)
{
if(x==n-1 and y==n-1)
{
sol[x][y]=1;
return true;
}
if(safe(x,y,n,maze[x][y]))
{
sol[x][y]=1;
if(solve_maze(maze,sol,n,x+1,y))
return true;
if(solve_maze(maze,sol,n,x,y+1))
return true;
sol[x][y]=0;
return false;
}
return false;
}
void solve()
{
ll maze[1005][1005];
ll sol[1005][1005];
ll n;
std::cin>>n; // input is n = 5
for(ll i=0;i<n;++i)
{
for(ll j=0;j<n;++j)
{
std::cin>>maze[i][j];
sol[i][j]=0;
}
}
if(solve_maze(maze,sol,n,0,0))
{
for(ll i=0;i<n;++i)
{
for(ll j=0;j<n;++j)
std::cout<<sol[i][j]<<" ";
std::cout<<"\n";
}
}
else
std::cout<<"No Solution Exist\n";
}
int main()
{
solve();
}