1. 程式人生 > >自動走迷宮(DFS)

自動走迷宮(DFS)

功能:

  • 輸入一張地圖,找出一條可到達終點的路徑,1代表不可走,0代表可走,2代表終點。

效果圖:

這裡寫圖片描述這裡寫圖片描述

實現原理:

  • DFS遍歷。
  • 二維陣列儲存地圖。
  • -

原始碼:

因為輸入資料太麻煩,附了組資料。

#include<stdio.h>
typedef struct
{
    int x;
    int y;
    int s;
    int f;
}note;

int map[999][999], book[999][999];
note queue[999];

int main()
{
    int n, i, j, head, tail, x, y, tx, ty, flag;
    int
drct[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}}; scanf("%d", &n); head = 1; tail = 1; x = 1; y = 1; //scanf("%d %d", &x, &y); queue[tail].x = x; queue[tail].y = y; queue[tail].s = 0; tail++; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { scanf
("%d", &map[i][j]); } } while (head < tail) { for (i = 0; i < 4; i++) { tx = queue[head].x + drct[i][0]; ty = queue[head].y + drct[i][1]; if (tx < 1 || tx > n || ty < 1 || ty > n) { continue
; } if (map[tx][ty] == 0 && book[tx][ty] == 0) { book[tx][ty] = 1; queue[tail].x = tx; queue[tail].y = ty; queue[tail].f = head; queue[tail].s = queue[head].s + 1; //printf("###%d %d\n", tail, queue[tail].f); tail++; } //printf("###%d %d %d %d %d %d\n", tail, queue[tail-1].f, queue[tail - 1].x, queue[tail - 1].y, tx, ty); if (map[tx][ty] == 2) { flag = 1; break; } } if (flag == 1) { break; } head++; } if (flag == 1) { map[tx][ty] = 3; for (;;) { map[queue[head].x][queue[head].y] = 3; //printf("%d %d %d\n", queue[head].x, queue[head].y, i);// if(head == 1) break; head = queue[head].f; //getchar(); } putchar('\n'); for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { if (map[i][j] == 3) printf("! "); else if (map[i][j] == 1) printf("# "); else printf("* "); } putchar('\n'); } } else printf("NO\n"); } /* 20 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 1 0 1 1 0 1 0 1 1 1 1 0 1 1 0 1 0 1 1 1 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 1 0 1 0 1 1 1 1 0 1 1 1 1 0 1 1 1 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1 0 1 1 1 1 0 1 1 0 1 0 1 1 1 1 0 1 1 2 */

PS:

當時剛從啊哈演算法上看到DFS,還沒實現過,第一次實現寫的這東西,也是感興趣,成就感滿滿!