原题:
There are black and white knights on a 5 by 5 chessboard. There are twelve of each color, and there is one square that is empty. At any time, a knight can move into an empty square as long as it moves like a knight in normal chess (what else did you expect?).
Given an initial position of the board, the question is: what is the minimum number of moves in which we can reach the final position which is:
Input
First line of the input file contains an integer N (N < 14) that indicates how many sets of inputs are there. The description of each set is given below:
Each set consists of five lines; each line represents one row of a chessboard. The positions occupied by white knights are marked by ‘0’ and the positions occupied by black knights are marked by ‘1. The space corresponds to the empty square on board.
There is no blank line between the two sets of input.
Note: The first set of the sample input below corresponds to this configuration:
Output
For each set your task is to find the minimum number of moves leading from the starting input config-
uration to the final one. If that number is bigger than 10, then output one line stating
Unsolvable in less than 11 move(s).
otherwise output one line stating
Solvable in n move(s).
where n ≤ 10.
The output for each set is produced in a single line as shown in the sample output.
Sample Input
2
01011
110 1
01110
01010
00100
10110
01 11
10111
01001
00000
Sample Output
Unsolvable in less than 11 move(s).
Solvable in 7 move(s).
中文:
题目很好理解,给你一个5×5的棋盘,上面有黑马和白马用1和0表示。现在问你,按照骑士在国际象棋中的行走规则,要想把棋盘摆成如第一张图的样子,最少需要多少步?如果大于10步就输出Unsolvable in less than 11 move(s). 小于10步输出 Solvable in 7 move(s).这里以7步为例
#include <bits/stdc++.h>
using namespace std;
unordered_set<string> us;
const string mark="111110111100 110000100000";
struct node
{
string s;
int num;
};
int n;
int bfs(node start)
{
queue<node> Q;
Q.push(start);
while(!Q.empty())
{
node head=Q.front();
Q.pop();
if(head.s==mark)
return head.num;
if(head.num>=10)
continue;
int blank_pos=head.s.find(' ');
int blank_row=blank_pos/5;
int blank_col=blank_pos%5;
for(int row=-2;row<=2;row++)
{
for(int col=-2;col<=2;col++)
{
if(abs(row)==abs(col)||row==0||col==0)
continue;
if(blank_row+row<0||blank_row+row>4||blank_col+col<0||blank_col+col>4)
continue;
int pos=(blank_row+row)*5+(blank_col+col);
node tmp=head;
swap(tmp.s[blank_pos],tmp.s[pos]);
if(us.find(tmp.s)!=us.end())
continue;
us.insert(tmp.s);
tmp.num++;
Q.push(tmp);
if(tmp.s==mark)
return tmp.num;
}
}
}
return 11;
}
int main()
{
ios::sync_with_stdio(false);
cin>>n;
cin.ignore();
while(n--)
{
us.clear();
string s;
for(int i=1;i<=5;i++)
{
string tmp;
getline(cin,tmp);
s+=tmp;
}
node start;
start.s=s;
start.num=0;
int ans=bfs(start);
if(ans<11)
cout<<"Solvable in "<<ans<<" move(s)."<<endl;
else
cout<<"Unsolvable in less than "<<11<<" move(s)."<<endl;
}
return 0;
}
解答:
要求最少步数,可以用广搜。状态保存可以用哈希表来实现,把棋盘弄成一维的字符串,可以自己写一个hash也可以用stl。这里面我偷了个懒,直接用的c++11当中的unordered_set,也就是哈希表来实现的判重的。其实这道题还有很多可以优化的地方,也可以用dfs做。