problem statement : http://www.spoj.com/problems/NAKANJ/ MY 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 is the reason of this weird output. logic and algorithm implementation seem fine to me . any help appreciated.
Your moves
array has 9 rows and 9 columns -
int moves[9][9];
While you return something from moves like this -
if(p.first==a2&&p.second==b2)
return moves[a2][b2];
Make a check whether a2 and b2 are less than 9 -
if(p.first==a2&&p.second==b2){
if(a2 < 9 && b2 <9){
return moves[a2][b2];
}
}
Your bfs()
function reaches the end while not returning anything, and it's expected to return int
.
That means that you are either ignoring compiler warnings or silencing them, in both cases it's a bad idea, turn warnings on and listen to them, they tell you that your code almost surely has bugs.
Also, don't do this
int s=d[0]-'a';int r=f[0]-'a';
it's too low quality code that makes your program alsmot impossible to understand, do it like this
int s;
int r;
s = d[0] - 'a';
r = f[0] - 'a';
I think this is likely the problem :
When you are casting a character which is not a digit, you should do :
int char_not_digit = char - 'a' ;
and when a digit to an int,
int char_digit = char - '0';
Look at the solution here
Thus all 0th position character in the input string should be casted to int
with subtracting 'a'
and all 1th position character in the input string should be casted to int
by subtracting '0'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.