本题难点有两个,一个是如何记录路径,还有就是如何设置障碍物,即障碍物的方向与扩展步数的方向要保持一致
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <stack>
#include <climits>
using namespace std;
int dx[] = {0,-1,0,1};
int dy[] = {1,0,-1,0}; //右上左下
int graph[9][9][4];
int dist[9][9] , pre[9][9][2] ; //pre是前驱坐标
int sx,sy,ex,ey;
int wx1,wy1,wx2,wy2;
void dfs(int x,int y,int cnt){
for(int i=0;i<4;i++){ //查看当前位置的四个方向是否可以走
if(graph[x][y][i]) continue; //若该方向不能走
//若该方向可以走,则沿着该方向进行扩展
int xx = x+dx[i]; //扩展新的位置
int yy = y+dy[i];
if(xx<1 || yy<1 || xx>6 || yy>6) continue;
if(cnt+1 > dist[xx][yy]) continue; //若当前的代价更大,则一定不能产生最优解
dist[xx][yy] = cnt+1;
pre[xx][yy][0] = x;
pre[xx][yy][1] = y;
dfs(xx,yy,cnt+1);
}
}
void path(){
int x = ex,y = ey; //倒序查找
int px = pre[x][y][0] , py = pre[x][y][1];
stack<char> st;
while(1){
if(x==px){ //同一行
if(py<y)
st.push('E');
else
st.push('W');
}
else{ //同一列
if(px<x)
st.push('S');
else
st.push('N');
}
if(px==sx && py==sy) break; //递归到了起点
x = px;
y = py;
px = pre[x][y][0];
py = pre[x][y][1];
}
while(!st.empty()){
printf("%c",st.top());
st.pop();
}
printf("\n");
}
int main(){
while(scanf("%d%d",&sy,&sx)){
if(sx==0 && sy==0) break;
scanf("%d%d",&ey,&ex);
//初始化
for(int i=0;i<9;i++)
for(int j=0;j<9;j++){
dist[i][j] = INT_MAX;
memset(graph,0,sizeof(graph));
}
//读取三个墙的位置,起点及终点
for(int i=0;i<3;i++){ //构造三面墙的矩阵
scanf("%d%d%d%d",&wy1,&wx1,&wy2,&wx2);
if(wx1==wx2){ //同一行
for(int j=wy1+1;j<=wy2;j++){
graph[wx1][j][3] = 1; //下部
graph[wx1+1][j][1] = 1; //上部
}
}
else{ //同一列
for(int j=wx1+1;j<=wx2;j++){
graph[j][wy1][0] = 1;
graph[j][wy1+1][2] = 1;
}
}
}
dfs(sx,sy,0); //起点,当前步数为0
path();
}
return 0;
}