[英]Unexpected Output of the program
問題陳述: http : //www.spoj.com/problems/NAKANJ/我的解決方案:
#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
這種奇怪輸出的原因是什么? 邏輯和算法實現對我來說似乎很好。 任何幫助表示贊賞。
您的moves
數組有9行9列-
int moves[9][9];
當您從這樣的動作中返回某些東西時-
if(p.first==a2&&p.second==b2)
return moves[a2][b2];
檢查a2和b2是否小於9-
if(p.first==a2&&p.second==b2){
if(a2 < 9 && b2 <9){
return moves[a2][b2];
}
}
您的bfs()
函數在不返回任何內容的情況下到達末尾,並且預計將返回int
。
這意味着您要么忽略編譯器警告,要么靜默它們,在兩種情況下都不是一個好主意,請打開警告並聆聽它們,它們告訴您您的代碼幾乎肯定存在錯誤。
另外,不要這樣做
int s=d[0]-'a';int r=f[0]-'a';
質量太低的代碼使您的程序無法理解,像這樣
int s;
int r;
s = d[0] - 'a';
r = f[0] - 'a';
我認為這可能是問題所在:
投射非數字字符時,應執行以下操作:
int char_not_digit = char - 'a' ;
當數字轉換為整數時,
int char_digit = char - '0';
在這里看解決方案
因此,輸入字符串中所有第0個位置字符都應減去'a'
強制轉換為int
,而輸入字符串中所有第1個位置字符應減去'0'
強制轉換為int
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.