这题算是bfs里比较复杂的一个题目了,一开始有点晕,还是看了紫书的解才写出的代码。
#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
struct Node {
int r, c, d;
string route;
Node(int _r, int _c, int _d) {
r = _r;
c = _c;
d = _d;
route = "";
}
};//行列面
const int dr[4] = { 0,-1,0,1 };
const int dc[4] = { 1,0,-1,0 };
const char *dct = "ENWS";
const char *turn = "LFR";
int pos[10][10][4][3];//r c d-t
bool jud[10][10][4];//判断结点某个值是否已经被加入队列
int fstr, fstc, lstr, lstc; char fstd;
int get_dctID(char c) {return strchr(dct, c)-dct;}
int get_turnID(char c) {return strchr(turn, c) - turn;}
Node walk(Node pos, char tn) {
int dct=pos.d;
if (get_turnID(tn) == 2)dct = (dct + 3) % 4;//turn right
if (get_turnID(tn) == 0)dct = (dct + 1) % 4;
return Node(pos.r+dr[dct],pos.c+dc[dct],dct);
}
void bfs() {
Node node(fstr, fstc, get_dctID(fstd));
queue<Node> Q;
node = walk(node, 'F');
node.route = node.route + " (" + (char)(fstr + 48) + ',' + (char)(fstc + 48) + ')' + ' ' + '(' + (char)(node.r + 48) + ',' + (char)(node.c + 48) + ')';
Q.push(node);
while (!Q.empty()) {
Node fnode = Q.front();
while (jud[fnode.r][fnode.c][fnode.d] == 1) {
Q.pop();
if (Q.empty()) {
cout << " No Solution Possible"<<endl;
return;
}
else fnode = Q.front();
}//判断是否循环查找
Q.pop();
if (fnode.r == lstr && fnode.c == lstc) {
cout << " ";
int j = 0, i = fnode.route.length();
for (j; j < i; j++) {
cout << fnode.route[j];
if (j % 59==0 && j) {
cout << endl << " ";
}
}
cout << endl;
return;
}
//如果到地方了
for (int i = 0; i < 3; i++) {
if (pos[fnode.r][fnode.c][fnode.d][i] == 1) {
Node nnode = walk(fnode, turn[i]);
nnode.route = fnode.route + " (" + (char)(nnode.r + 48) + ',' + (char)(nnode.c + 48) + ')';
Q.push(nnode);
}
}
jud[fnode.r][fnode.c][fnode.d] = 1;
}
cout << " No Solution Possible"<<endl;
}
int main() {
//row column dct 行列 方向
memset(pos, 0, sizeof(pos));
string ss;
while (cin >> ss &&ss!="END") {
cin >> fstr >> fstc >> fstd >> lstr >> lstc;
pos[fstr][fstc][0][0] = get_dctID(fstd);//第一组第一个字母
int r, c; char dt[5];
while (cin >> r && r) {//保存坐标 如果不为0则继续
cin >> c;
while (cin >> dt && dt[0] != '*') {
int i = 1;//dt是字符型
while (dt[i++])
pos[r][c][get_dctID(dt[0])][get_turnID(dt[i - 1])] = 1;
}
}//节点保存面朝的方向,变量保存可以移动的方向 如果有这个方向则为1 例如 第一行 第二列 面朝东如果存在向右转则 pos[1][2][0][2]=1; 缺点是时间复杂度增加到最大值,优点是比较直观。
cout << ss << endl;
bfs();
}
return 0;
}