今天学了搜索, 不过暂时还停留在较为初级的阶段
这节介绍DFS和回溯.
这道题不是裸的深搜题, 中间要记录走过的点, 用vector结构体储存
期间出过几个小错误, 比如边界条件弄错
发现这种格式比较复杂的题目中, 还是用printf()函数比较舒服
难怪Python也是这样用的
注意回溯法的几个要点
- 初始状态
- 目标状态
- 状态恢复 // 尤其要注意
DFS的核心是递归地建立一棵搜索树, 用剪枝来进行优化
尤其要理解搜索树这个概念, 因为理解了搜索树, 就能比较形象地理解DFS地含义了
剪枝的过程中计算一些作为条件的变量所花费的时间称为代价
#include <bits/stdc++.h>
using namespace std;
bool Map[16][16] = {}, vis[16][16] = {};
int sx, sy, ex, ey, m, n, ans = 0;
vector <pair<int, int> >loc;
void dfs(int x, int y)
{
//cout << "x = " << x << ' ' << "y =" << y << endl;
if(x == 0 || y == 0 || x == m+1 || y == n+1)
return;
if(vis[x][y] || !Map[x][y]) return;
vis[x][y] = 1; loc.push_back(make_pair(x, y));
dfs(x, y - 1);
dfs(x - 1, y);
dfs(x, y + 1);
dfs(x + 1, y);
if(x == ex && y == ey) {
ans++;
vector <pair<int, int> >::iterator it = loc.begin();
printf("(%d,%d)", it->first, it->second);
it++;
while(it != loc.end()) {
printf("->(%d,%d)", it->first, it->second);
it++;
}
cout << endl;
}
vis[x][y] = 0; loc.pop_back();
//cout << "in the end : x = " << x << ' ' << "y =" << y << endl;
}
int main()
{
cin >> m >> n;
for(int i = 1; i <= m; ++i) {
for(int j = 1; j <= n; ++j) {
cin >> Map[i][j];
}
}
cin >> sx >> sy >> ex >> ey;
dfs(sx, sy);
if(ans == 0) cout << -1;
}