Luogu P1189 SEARCH
本题正解为DFS与剪枝
因为本题是寻找所有道路的所有终点,因此应该采用搜索。因为道路不是向四周无限延伸,而是在城市中七拐八绕的,因此适宜采用深度优先搜索(广度优先搜索也可以,但是做法是用BFS去模拟DFS,何必呢…)
基础版(30分)很简单,就是对于每个方向,持续向前行进。对于途径的每一个点,转向,如果转向后到达的新点可以通行,那么就进入下一个方向重新进行上述操作;如果转向后到达的新点不可以通行,那么就停止,不再向这个方向行进。
但是这种方法的劣势明显,即搜索到的方向太多,路径太长,耗时太长。但是经过分析我们知道,如果在第i个方向中,两条路径都经过同一个点,那么其中一条路(后经过的这个点的路)就无需继续前进,因为前方两条路径将会重叠。
同时,因为车可能会绕圈,返回到原先的道路上,因此不同次数但同一方向上走过并不互相影响。
如图,4 -> 3 -> 5 -> 0 -> 1 -> 2
与4 -> 3 -> 1 -> 2
都经过1,2,途径1,2时均为向南行进,重复
如图,若是8->1->2->3->4->5->6->7->8->1->2
,在8,1,2这条路上,均为向南行进,且在第一次转向前这几点都走过,但是因为终点是2,因此必须要走完。所以不同转向次数不会相互影响剪枝
#include <iostream>
#include <cstring>
#include <string>
#include <cstdio>
using namespace std;
char town[55][55], ans[55][55];
int n, m;//行、列
int sx, sy;//起始坐标
int direc_num, direc[1005];//方向数,每个方向
//转向数组
int cx[5]{0, 1, -1, 0, 0};
int cy[5]{0, 0, 0, 1, -1};
bool vis[55][55][1005];//剪枝,判断在第step个方向时这一点是否走过
string dir;
void pre(){
cin >> n >> m;//输入行与列
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++){
cin >> town[i][j];//输入道路情况
ans[i][j] = town[i][j];
if(town[i][j] == '*'){
sx = i, sy = j;//记录起点
ans[i][j] = '.';//起点可通行
}
}
cin >> direc_num;//总方向数
for(int i = 1; i <= direc_num; i++){
cin >> dir;
//与转向数组对应
if(dir == "EAST")direc[i] = 3;//x, y+1即向东走一步
if(dir == "SOUTH")direc[i] = 1;//x+1, y即向南走一步
if(dir == "WEST")direc[i] = 4;//x, y-1即向西走一步
if(dir == "NORTH")direc[i] = 2;//x-1, y即向北走一步
}
}
bool check(int x, int y, int step){
if(x < 1 || x > n || y < 1 || y > m)return 0;//判断是否越界
if(town[x][y] == 'X')return 0;//判断是否可以通行
if(vis[x][y][step])return 0;//判断这一点在第step个方向时是否走过
return 1;
}
void search(int x, int y, int step){//step表示当前是第几个方向
if(step == direc_num+1){//所有方向均已移动完毕
ans[x][y] = '*';//记录终点
return ;
}
for(int i = 1; ; i++){//朝这一方向行进
//行进不同距离
int xx = x + i * cx[direc[step]];
int yy = y + i * cy[direc[step]];
if(check(xx, yy, step)){//如果可以走
vis[xx][yy][step] = 1;//标记在本次走过
search(xx, yy, step+1);//转向
}
else break;//如果不可以走,就停止行进
}
}
void print(){
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
cout << ans[i][j];
}
cout << endl;
}
}
int main(){
//freopen("code.in", "r", stdin);
//freopen("code.out", "w", stdout);
pre();
search(sx, sy, 1);//从起点,向第一个方向行进
print();
return 0;
}