c++ - Unexpected Output of the program -


problem statement : http://www.spoj.com/problems/nakanj/ solution:

#include<bits/stdc++.h> using namespace std; int x[10]={0,2,2,-2,-2,1,1,-1,-1}; int y[10]={0,1,-1,1,-1,2,-2,2,-2}; int bfs(int a1,int b1,int a2,int b2) {     pair<int,int> p;     int i;     queue<pair<int,int> >q;     int moves[9][9],visit[9][9],m,n;     memset(moves,0,sizeof(moves));     memset(visit,0,sizeof(visit));     p.first=a1;     p.second=b1;     q.push(p);     moves[a1][b1]=0;     while(!q.empty())     {         p=q.front();         q.pop();         if(p.first==a2&&p.second==b2)             return moves[a2][b2];         for(i=1;i<=8;i++)         {             m=p.first+x[i];             n=p.second+y[i];             if(m>8||m<1||n>8||n<1)                 continue;             else             {                 visit[m][n]=1;                 moves[m][n]=moves[p.first][p.second]+1;                 q.push(make_pair(m,n));             }         }     } } int main() {     long long int t;     cin>>t;     while(t--)     {         string d,f;         cin>>d>>f;         int s=d[0]-'a';int r=f[0]-'a';         cout<<bfs(s+1,(int)d[1],r+1,(int)f[1])<<endl;     }     return 0; } 

input : 3 a1 h8 a1 c2 h8 c3  output : -1217403904 -1217403904  -1217403904 

what reason of weird output. logic , algorithm implementation seem fine me . appreciated.

your moves array has 9 rows , 9 columns -

int moves[9][9];   

while return moves -

if(p.first==a2&&p.second==b2)    return moves[a2][b2]; 

make check whether a2 , b2 less 9 -

if(p.first==a2&&p.second==b2){    if(a2 < 9 && b2 <9){     return moves[a2][b2];   } } 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -