1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
| #include <stdio.h> struct node { int x; int y; int s; }; int main() { struct node que[2501]; int i,j, startx, starty, q, p,head,tail,n,m,k,tx,ty,flog; int a[50][50] = { 0 }; int book[50][50] = { 0 }; printf("请输入你要输入几行几列的迷宫:"); scanf_s("%d %d", &n, &m); printf("请输入你要输入的迷宫(0表示路,1表示障碍):"); for(i=1;i<=n;i++) for (j = 1; j <= m; j++) { scanf_s("%d", &a[i][j]); } printf("请输入初始位置:"); scanf_s("%d %d", &startx, &starty); printf("请输入小哈的位置:"); scanf_s("%d %d", &p, &q); tail = 1; head = 1; que[tail].x = startx; que[tail].y = starty; que[tail].s = 0; tail++; book[startx][starty] = 1; flog = 0; int next[4][2] = { {1,0}, {0,1}, {-1,0}, {0,-1} }; while (head < tail) { for (k = 0; k <= 3; k++) {
tx = que[head].x + next[k][0]; ty = que[head].y + next[k][1]; if (tx<1 || tx>n || ty<1 || ty>m) { continue; } if (book[tx][ty] == 0 && a[tx][ty] == 0) { book[tx][ty] = 1; que[tail].x = tx; que[tail].y = ty; que[tail].s = que[head].s + 1; tail++; } if (tx == p && ty == q) { flog = 1; break; } } if (flog == 1) { break; } head++; } printf("最少要走%d步。", que[tail -1].s); getchar(); getchar(); return 0; }
|