#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
struct Point {
int x;
int y;
Point(int x_,int y_):x(x_),y(y_){}
};
int map[7][7];
int pace[7][7];
int rout[7][7];
int f(int p) {
for (int x = 1; x <= 5; x++) {
for (int y = 1; y <= 5; y++) {
if (pace[x][y] == p) {
if (x == 5 && y == 5)
return 1;
if (map[x][y + 1] == 0 && pace[x][y + 1] == -1)
pace[x][y + 1] = p + 1;
if (map[x][y - 1] == 0 && pace[x][y - 1] == -1)
pace[x][y - 1] = p + 1;
if (map[x+1][y] == 0 && pace[x+1][y] == -1)
pace[x+1][y] = p + 1;
if (map[x-1][y] == 0 && pace[x-1][y] == -1)
pace[x-1][y] = p + 1;
}
}
}
return 0;
}
Point find(int x, int y, int p) {
if (pace[x][y + 1] == p - 1)
return Point(x, y + 1);
if (pace[x][y - 1] == p - 1)
return Point(x, y - 1);
if (pace[x - 1][y] == p - 1)
return Point(x - 1, y);
if (pace[x + 1][y] == p - 1)
return Point(x + 1, y);
}
int main() {
for (int x = 1; x <= 5; x++) {
for (int y = 1; y <= 5; y++)
cin >> map[x][y];
}
for (int i = 0; i <= 5 + 1; i++) {
map[i][0] = 1, map[i][5 + 1] = 1;
}
for (int j = 0; j <= 5 + 1; j++) {
map[0][j] = 1, map[5 + 1][j] = 1;
}
memset(pace, -1, sizeof(pace));
pace[1][1] = 0;
int p = 0;
while (true) {
int t = f(p);
if (t == 1)
break;
p++;
}
stack<Point> s;
s.push(Point(5, 5));
while (p > 0) {
Point temp = find(s.top().x, s.top().y, p);
s.push(temp);
p--;
}
while (s.size() != 0) {
cout << '(' << s.top().x - 1 << ", " << s.top().y - 1 << ')';
s.pop();
if (s.size() != 0)
cout << endl;
}
return 0;
}
[Coursera]算法基础_Week7_广搜_Q2
最新推荐文章于 2015-12-15 21:36:38 发布