题意描述:
8*8的棋盘里给出起点和目标,找到两点之间的最近距离并打印路径;从一个点可以向8个方向走;
这道题wa了一遍,对了一下错误数据才看到错在了哪里,
找到目标后向起点回溯的条件是:tmpx != startx || tmpy != starty而不是 &&
另外, 在使用题目的测试数据时,发现循环里的回溯的等式和记录路径的方式也不正确
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<string.h>
#include<algorithm>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 8;
string c[maxn][maxn];
bool visit[maxn][maxn];
int dir[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
char dirname[8][5] = {"LU","U","RU","L","R","LD","D","RD"};
int prevrec[maxn][maxn];
bool valid(int x, int y){
return (x>=0 && x<8 && y >= 0 && y < 8 && !visit[x][y]);
}
class node{
public:
int x, y, step;
string dir;
node(int x_, int y_,int step_):x(x_),y(y_),step(step_){}
};
int main(){
//freopen("1.txt","r",stdin);
string start, end;
cin >> start >> end;
if(start == end){
cout << "0" << endl;
return 0;
}
memset(visit, 0, sizeof(visit));
int startx,starty, endx, endy;
for(int i = 0; i < 8; ++i){
for(int j = 0; j < 8; ++j){
char lineid = 8 - i + '0';
char columnid = 'a' + j;
c[i][j] = "";
c[i][j] += columnid;
c[i][j] += lineid;
if(c[i][j] == start){
startx = i;
starty = j;
visit[i][j] = true;
}
if(c[i][j] == end){
endx = i;
endy = j;
}
}
}
queue<node> q;
q.push(node(startx,starty,0));
vector<string> route;
while(!q.empty()){
node tmp = q.front();
q.pop();
if(tmp.x == endx && tmp.y == endy){
cout << tmp.step << endl;
int tmpx = tmp.x, tmpy = tmp.y;
// cout << tmpx << "\t" << tmpy << endl;
// cout << "start " << startx << "\t" << starty << endl;
while(tmpx != startx || tmpy != starty){
// cout << "enter while" << endl;
// cout << tmpx << "\t" << tmpy << endl;
int tmpidx = prevrec[tmpx][tmpy];
route.push_back(dirname[tmpidx]);
tmpx += dir[tmpidx][0] * (-1);
tmpy += dir[tmpidx][1] * (-1);
}
break;
}
else{
for(int i = 0; i < 8; ++i){
int ttmpx = tmp.x + dir[i][0];
int ttmpy = tmp.y + dir[i][1];
string tmpdir = dirname[i];
int tmpstep = tmp.step;
if(valid(ttmpx,ttmpy)){
node tmpnode(ttmpx, ttmpy,tmpstep+1);
prevrec[ttmpx][ttmpy] = i;
q.push(tmpnode);
visit[ttmpx][ttmpy] = true;
}
}
}
}
int vecsize = route.size();
for(int j = vecsize - 1; j >= 0; --j){
cout << route[j] << endl;
}
return 0;
}