一、题目链接
二、题目分析
(一)算法标签
搜索 DFS
(二)解题思路
三、AC代码
解法一:(DFS)
#include <iostream>
#include <vector>
using namespace std;
const int N = 15;
int n, m;
int g[N][N];
bool st[N][N], has_solution;
int dx[4] = {0, -1, 0, 1}, dy[4] = {-1, 0, 1, 0};
struct Point {
int x, y;
};
vector<Point> track; // 存放路径
Point start, dest;
istream& operator>> (istream &in, Point &p)
{
in >> p.x >> p.y;
return in;
}
ostream& operator<< (ostream &out, Point &p)
{
out << '(' << p.x << ',' << p.y << ')';
return out;
}
bool operator== (Point &p1, Point &p2)
{
return p1.x == p2.x && p1.y == p2.y;
}
void printTrack()
{
cout << track[0];
for (int i = 1; i < track.size(); i ++ )
cout << "->"<< track[i];
cout << endl;
}
void dfs(Point p)
{
if (p == dest)
{
has_solution = true;
printTrack();
return;
}
for (int i = 0; i < 4; i ++ )
{
int a = p.x + dx[i], b = p.y + dy[i];
if (a < 1 || a > n || b < 1 || b > m) continue;
if (g[a][b] == 1 && !st[a][b])
{
st[a][b] = true;
track.push_back({a, b});
dfs({a, b});
track.pop_back();
st[a][b] = false;
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> g[i][j];
cin >> start >> dest;
// 起点被访问,并放进track
st[start.x][start.y] = true;
track.push_back(start);
dfs(start);
if (!has_solution) cout << "-1" << endl;
return 0;
}
DFS另一种写法
#include <iostream>
using namespace std;
const int N = 15;
int g[N][N];
bool st[N][N];
int n, m, sx, sy, fx, fy;
int dx[4] = {0, -1, 0, 1}, dy[4] = {-1, 0, 1, 0};
bool has_solution;
void dfs(int x, int y, string s)
{
if (x == fx && y == fy)
{
has_solution = true;
cout << s << endl;
return;
}
for (int i = 0; i < 4; i ++ )
{
int a = x + dx[i], b = y + dy[i];
if (a >= 1 && a <= n && b >= 1 && b <= m
&& !st[a][b] && g[a][b] == 1)
{
st[a][b] = true;
dfs(a, b, s + "->(" + to_string(a) + "," + to_string(b) + ")");
st[a][b] = false;
}
}
}
int main()
{
cin >> n >> m;
for (int i = 1; i <= n; i ++ )
for (int j = 1; j <= m; j ++ )
cin >> g[i][j];
cin >> sx >> sy >> fx >> fy;
st[sx][sy] = true;
dfs(sx, sy, "(" + to_string(sx) + "," + to_string(sy) + ")");
if (!has_solution) cout << "-1" << endl;
return 0;
}