題目串連:http://acm.pku.edu.cn/JudgeOnline/problem?id=1657
版本一:
1,用廣搜求王的最小步數,這裡出了一些問題:在元素入隊時不設定被訪標誌,而是在出隊時才設定被訪標誌,這就存在問題了,因為一個標誌可能被隊列中多個相鄰的節點同時發現這樣就會時同一個元素多次入隊,被多次訪問;看了一下算導上的思想,發現了這個錯誤,算導上將每個節點的被訪程度分為未發現、發現、已訪問,進入隊列的只能是未發現態。所以一個節點只要被發現就應該設定標誌,不能再排入佇列了。
2,象不能一步達到時的走法只能有兩種情況:
M 或者 A B
A B M
容易推出來A和B應該滿足的條件
3,還要處理好源點和終點相同的特殊情況。
#include <iostream>
using namespace std;
struct Point
{
int r;
int c;
int step;
};
int t,r1,r2,r3,r4;
char r,c;
Point org,des;
Point q[64];
int hd,tl;
bool visit[8][8];
void BFS()
{
memset(visit,false,sizeof(visit));
hd = tl = 0;
org.step = 0;
q[tl++] = org;
visit[org.r][org.c] = true;
int i;
Point cur,next;
int offset[8][2] = {{0,1},{1,0},{0,-1},{-1,0},{1,-1},{-1,1},{1,1},{-1,-1}};
while(hd != tl)
{
cur = q[hd++];
// visit[cur.r][cur.c] = true;
for(i = 0;i < 8;++i)
{
next.r = cur.r + offset[i][0];
next.c = cur.c + offset[i][1];
if(next.r >= 0 && next.r < 8 && next.c >= 0 && next.c < 8 &&
!visit[next.r][next.c])
{
next.step = cur.step + 1;
q[tl++] = next;
visit[next.r][next.c] = true;
if(next.r == des.r && next.c == des.c)
break;
}
}
if(next.r == des.r && next.c == des.c)
{
des.step = next.step;
break;
}
}
}
int main()
{
freopen("in.txt","r",stdin);
cin >> t;
while(t--)
{
cin >> c >> r;
org.r = r - '1';
org.c = 7 + 'a' - c;
cin >> c >> r;
des.r = r - '1';
des.c = 7 + 'a' - c;
if(des.r == org.r && des.c == org.c)
{
cout << 0 << ' ' << 0 << ' ' << 0 << ' ' << 0 << endl;
continue;
}
BFS();
cout << des.step << ' ';
if(abs(des.r-org.r) == abs(des.c - org.c) || des.r == org.r || des.c == org.c)
cout << 1 << ' ';
else
cout << 2 << ' ';
if(des.r == org.r || des.c == org.c)
cout << 1 << ' ';
else
cout << 2 << ' ';
if(abs(des.r-org.r) == abs(des.c - org.c))
cout << 1 << endl;
else if((abs(des.r-org.r) + abs(des.c - org.c)) % 2 == 0)
cout << 2 << endl;
else
cout << "Inf" << endl;
}
return 0;
}
版本二:各種棋子步數都可以通過公式計算出來,王的也不例外!
#include <iostream>
using namespace std;
int main()
{
freopen("in.txt","r",stdin);
int t,x,y,o1,o2,o3,o4;
char c1,r1,c2,r2;
cin >> t;
while(t--)
{
cin >> c1 >> r1 >> c2 >> r2;
if(r1 == r2 && c1 == c2)
{
printf("0 0 0 0/n");
continue;
}
x = abs(c1-c2);
y = abs(r1-r2);
o1 = x > y ? x : y;
if(x == y || r1 == r2 || c1 == c2)
o2 = 1;
else
o2 = 2;
if(r1 == r2 || c1 == c2)
o3 = 1;
else
o3 = 2;
if(x == y)
o4 = 1;
else if((x+y) % 2 == 0)
o4 = 2;
else
o4 = -1;
if(o4 == -1)
printf("%d %d %d %s/n",o1,o2,o3,"Inf");
else
printf("%d %d %d %d/n",o1,o2,o3,o4);
}
return 0;
}