ラビリンス問題(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)
", 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("
"); } else { printf("-1
"); } } } // 9 9 0 1 1 1 1 1 1 1 0 1 1 0 0 0 0 0 0 1 0 0 1 0 1 1 0 1 0 1 1 0 0 0 0 0 0 0 0 1 0 0 0 1 1 0 0 1 0 0 0 1 0 0 0 0 1 1 0 0 0 0 0 0 0 0 2 8 8 2