思路
简单的搜索,记录一下路径即可,
数据范围过小,可采用各种搜索方法,此处展示 (bfs) 做法,仅供参考。
代码
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#include <utility>
using namespace std;
typedef pair <int ,int > pa;
const int MAXN = 5 + 10;
int n ,g[MAXN][MAXN] ,path[MAXN][MAXN];
int dir[4][2] = {{1 ,0} ,{0 ,1} ,{-1 ,0} ,{0 ,-1}};
pa ans[MAXN * MAXN];
int tot = 0;
void bfs () {
queue <pa > s;
int vis[MAXN][MAXN];
bool ok = false;
memset (vis ,0 ,sizeof (vis));
memset (path ,-1 ,sizeof (path));
s.push(make_pair (0 ,0));
vis[0][0] = 1;
while (! s.empty()) {
if (ok) break;
int x = s.front().first ,y = s.front().second;
s.pop();
for (int q = 0;q < 4;++ q) {
int x_ = x + dir[q][0] ,y_ = y + dir[q][1];
if (x_ < 0 || y_ < 0 || x_ > n || y_ > n) continue;
if (! vis[x_][y_] && g[x_][y_] == 0) {
path[x_][y_] = q;
vis[x_][y_] = 1;
if (y_ == n && x_ == n) ok = true;
s.push(make_pair (x_ ,y_));
}
}
}
return ;
}
int main () {
n = 5;
for (int q = 0;q < n;++ q) {
for (int w = 0;w < n;++ w) {
scanf ("%d",&g[q][w]);
}
}
bfs ();
int x = 4 ,y = 4;
while (x != 0 || y != 0) {
if (path[x][y] == 0) {
ans[++ tot] = make_pair (x ,y);
x --;
}
else if (path[x][y] == 1) {
ans[++ tot] = make_pair (x ,y);
y --;
}
else if (path[x][y] == 2) {
ans[++ tot] = make_pair (x ,y);
x ++;
}
else if (path[x][y] == 3) {
ans[++ tot] = make_pair (x ,y);
y ++;
}
}
printf ("(%d, %d)
",0 ,0);
for (int q = tot;q >= 1;-- q) {
printf ("(%d, %d)
",ans[q].first ,ans[q].second);
}
return 0;
}