心得·:
bfs设置状态时: 在该节点变为死结点时设置状态。即在出队列的时候设置状态位,不是在入队列的时候设置状态位
输入数据有空格:
可以使用getline(), 但在使用getline之前有使用cin的话, 需要把输入中间的回车清空:
例如:
while(cin >> c >> r && r){
string str;
memset(g,0,sizeof(g));
getline(cin, str); //清空cin
for(int i = 1; i <= r; i++){
getline(cin, str);//输入有空格
for(int j = 1; j <= c; j++){
g[i][j] = str[j - 1];
}
}
}
AC代码:
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<iostream>
#include<set>
#include<cmath>
using namespace std;
struct Node{
int x,y;
int steps;
int dir;
bool operator <(const Node& t1) const{
return this->steps > t1.steps;
}
};
char g[80][80];
bool vis[80][80];
int dir[4][2] = {{1,0},{-1,0},{0,1},{0,-1}};
int segments;
int r,c;
bool bfs(int x1,int y1,int x2,int y2){
priority_queue<Node> q;
Node newnode,topNode;
newnode.x = x1;
newnode.y = y1;
newnode.dir = -1;
newnode.steps = 1;
q.push(newnode);
while(!q.empty()){
topNode = q.top();
q.pop();
int ci,cj;
vis[topNode.x][topNode.y] = true;
if(topNode.x == x2 && topNode.y == y2){
segments = topNode.steps;
return true;
}
//cout << topNode.y << " " << topNode.x << " " << topNode.steps << endl;
for(int i = 0; i < 4; i++){
ci = topNode.x + dir[i][0];
cj = topNode.y + dir[i][1];
newnode.x = ci;
newnode.y = cj;
if(ci < 0 || ci > r + 1 || cj < 0 || cj > c + 1)
continue;
//newnode.Len = sqrt((ci - x2) * (ci - x2) + (cj - y2) * (cj - y2));
// cout << cj << " " << ci << " " << topNode.steps << endl;
if(!vis[ci][cj]){
if(topNode.dir == -1){
newnode.dir = i;
}else if(topNode.dir != i){
newnode.steps = topNode.steps + 1;
}else
newnode.steps = topNode.steps;
newnode.dir = i;
if(g[ci][cj] == 'X'){
if(ci == x2 && cj == y2)
q.push(newnode);
continue;
}
q.push(newnode);
}
}
// cout << "---\n";
}
return false;
}
int main(){
int t = 0;
int x1,x2,y1,y2,tt;
while(cin >> c >> r && r){
string str;
memset(g,0,sizeof(g));
getline(cin, str);
for(int i = 1; i <= r; i++){
getline(cin, str);
for(int j = 1; j <= c; j++){
g[i][j] = str[j - 1];
}
}
printf("Board #%d:\n",++t);
tt = 0;
while(true){
cin >> x1 >> y1 >> x2 >> y2;
if(x1 == 0) break;
memset(vis,0,sizeof(vis));
if(bfs(y1,x1,y2,x2))
printf("Pair %d: %d segments.\n",++tt,segments);
else
printf("Pair %d: impossible.\n",++tt);
}
cout << endl;
}
}