迷宫问题(DFS实现)
#include <iostream>#include <stack>#include <cstdio>using namespace std;const int maxn = 100;int n = 0, m = 0;int startx = 0, starty = 0;int exitx = 0, exity = 0;int map[maxn][maxn];int dx[4] = {0, 1, 0, -1};int dy[4] = {1, 0, -1, 0};int flag[maxn][maxn];typedef struct { int x; int y;}point;point path[100];stack<point> mys;//栈int search() { int s[10000]; int x = startx, y = starty; int newx = 0, newy = 0; int step = 0; point cur; cur.x = x;//当前点的坐标 cur.y = y; flag[x][y] = 1; mys.push(cur); step = 1; while (step > 0) { s[step]++; if (s[step] == 4) { step--; if (!mys.empty()) { mys.pop(); } if (!mys.empty()) { x = (mys.top()).x; y = (mys.top()).y; } } else { newx = x + dx[s[step]]; newy = y + dy[s[step]]; if (!map[newx][newy] && !flag[newx][newy]) { cur.x = newx; cur.y = newy; printf("(%d, %d)\n", cur.x, cur.y); //getchar(); mys.push(cur); if (newx==exitx && newy==exity) { return 1; } x = newx; y = newy; flag[newx][newy] = 1; step++; s[step] = -1; } } } return -1;}int main(){ while (2 == scanf("%d%d", &n, &m)) { for (int i = 1; i < n; i++) {//输入数据 for (int j = 1; j < m; j++) { scanf("%d", &map[i][j]); } } for (int i = 0; i <= n; i++) {//第一列和最后一列。 map[i][0] = 1; map[i][m] = 1; } for (int i = 0; i <= m; i++) {//第一行和最后一行 map[0][i] = 1; map[n][i] = 1; } //------------------------------------- cout << endl; for (int i = 0; i <= n; i++) { //输出完整的图看一看。 for (int j = 0; j <= m; j++) { printf("%d ", map[i][j]); } cout << endl; } cout << endl; //-------------------------------------- scanf("%d%d", &startx, &starty);//输入起始点和出口。 scanf("%d%d", &exitx, &exity); int res = search(); if (1 == res) { point v[maxn]; int i = 0; while (!mys.empty()) { v[i++] = mys.top(); mys.pop(); } for (int j = i-1; j >= 0; j--) { printf("(%d, %d)", v[j].x, v[j].y); if (j > 0) { printf(" ---> "); } } printf("\n"); } else { printf("-1\n"); } }}//测试数据9 90 1 1 1 1 1 1 10 1 1 0 0 0 0 00 1 0 0 1 0 1 10 1 0 1 1 0 0 00 0 0 0 0 1 0 00 1 1 0 0 1 0 00 1 0 0 0 0 1 10 0 0 0 0 0 0 02 88 2