#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct Pos { int x; int y; }Pos; typedef struct SqStack { Pos data[200]; int top; }SqStack; void Push(SqStack* S, Pos e) { S->top++; S->data[S->top].x = e.x; S->data[S->top].y = e.y; } void Pop(SqStack* S, Pos* e) { e->x = S->data[S->top].x; e->y = S->data[S->top].y; S->top--; } int Empty(SqStack* S) { return S->top == -1; } void Init(SqStack* S) { S->top = -1; } //maze[i][j] 1表示障碍,0表示通路,返回路径 SqStack* MazePath(int maze[10][10], Pos start, Pos end) { int m[10][10]; memcpy(m, maze, 10 * 10 * sizeof(int)); SqStack* S = (SqStack*)malloc(sizeof(SqStack)); Init(S); Pos curpos = start; if (m[curpos.y-1][curpos.x-1] == 0) { m[curpos.y - 1][curpos.x - 1] = 3; Push(S, curpos); if (curpos.x == end.x&&curpos.y == end.y) return S; else curpos.x++; } else { return NULL; } while (!Empty(S)) { if (m[curpos.y - 1][curpos.x - 1] == 0) { m[curpos.y - 1][curpos.x - 1] = 3; Push(S, curpos); if (curpos.x == end.x&&curpos.y == end.y) return S; else curpos.x++; } else { Pos prepos; Pop(S, &prepos); if (curpos.x > prepos.x) { curpos.x = prepos.x; curpos.y = prepos.y + 1; Push(S, prepos); } else if (curpos.y > prepos.y) { curpos.x = prepos.x - 1; curpos.y = prepos.y; Push(S, prepos); } else if (curpos.x < prepos.x) { curpos.x = prepos.x; curpos.y = prepos.y - 1; Push(S, prepos); } else { m[prepos.y - 1][prepos.x - 1] = 2; curpos = prepos; } } } return NULL; } void main() { int maze[10][10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }; Pos start = { 2,2 }; Pos end = { 9,9 }; SqStack* S = MazePath(maze, start, end); SqStack path; Init(&path); if (S) { while (!Empty(S)) { Pos p; Pop(S, &p); Push(&path, p); } free(S); } else { printf("不存在路径"); } while (!Empty(&path)) { Pos p; Pop(&path, &p); printf("(%d,%d)\n", p.x,p.y); } getchar(); }
数据结构(C语言) 栈的应用之迷宫求解
猜你喜欢
转载自www.cnblogs.com/wumingoo1/p/11165990.html
今日推荐
周排行