//queue.h
#ifndef queue_h
#define queue_h
#include <stdlib.h>
#include <iostream>
struct point
{
public:
int index;
int x;
int y;
int pre;
};
struct queue
{
private:
struct Node
{
point data;
Node *next;
};
Node *front;
Node *rear;
public:
void init()
{
rear = (Node *)malloc(sizeof(Node));
front = (Node *)malloc(sizeof(Node));
rear = front;
front->next = nullptr;
}
void enqueue(const point & pt)
{
Node *nd;
nd = (Node *)malloc(sizeof(Node));
nd->data = pt;
nd->next = rear->next;
rear->next = nd;
rear = nd;
rear->next = NULL;
}
bool dequeue(point & pt)
{
if(is_empty())
return false;
else
{
Node *nd;
nd = (Node *)malloc(sizeof(Node));
nd = front->next;
pt = nd->data;
front->next = nd->next;
delete nd;
return true;
}
}
bool is_empty()
{
return front->next == NULL;
}
void destroy()
{
point pt;
while(!is_empty())
{
dequeue(pt);
}
delete front;
}
bool member(point & pt, int i)
{
Node *nd ;
nd = (Node *)malloc(sizeof(Node));
nd = front->next;
int count = 0;
for(; count < i; count++)
{
if(nd == NULL)
return false;
pt = nd->data;
nd = nd->next;
}
return true;
}
point head()
{
return front->next->data;
}
void display()
{
Node *nd ;
nd = (Node *)malloc(sizeof(Node));
nd = front->next;
while(nd != NULL)
{
std::cout << nd->data.index << " " << nd->data.x << " " << nd->data.y << " " << nd->data.pre << "\\";
nd = nd->next;
}
}
};
#endif
//main.cpp
#include "queue.h"
const int M = 8, N = 8;
int mg[M+2][N+2] =
{
{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,1,1,1,1,1,1,1,1,1}
};
bool mgpath(int x1, int y1, int m, int n);
int main()
{
if(!mgpath(1,1,M,N))
std::cout << "该迷宫问题没有解!" << std::endl;
return 0;
}
bool mgpath(int x1, int y1, int m, int n)
{
// 从入口开始,将四个方向中mg为零的点均入队,按顺序写入index和pre(上一点index)
// 按index顺序选择当前点,直到找到出口
// 找到出口后,按出口pre的值找对应index的点出队并输出点信息
if(m > M || n > N || !mg[m][n])
return false;
int x = x1;
int y = y1;
int x_next = 0, y_next = 0;
queue q_mg;
q_mg.init();
int id = 1, id_xy = 1;
int dir;
point pt;
pt.x = x1;
pt.y = y1;
pt.index = id;
pt.pre = 0;
q_mg.enqueue(pt);
mg[x1][y1] = -1;
bool end = false;
while(!end)
{
for(dir = 0; dir < 4; dir++)
{
switch(dir)
{
case 0: x_next = x-1;
y_next = y;
break;
case 1: x_next = x;
y_next = y+1;
break;
case 2: x_next = x+1;
y_next = y;
break;
case 3: x_next = x;
y_next = y-1;
break;
}
if(!mg[x_next][y_next])
{
pt.x = x_next;
pt.y = y_next;
pt.pre = id_xy;
id++;
pt.index = id;
q_mg.enqueue(pt);
mg[x_next][y_next] = -1;
if(x_next == m && y_next == n)
end = true;
}
}
id_xy++;
if(q_mg.member(pt, id_xy))
{
x = pt.x;
y = pt.y;
}
else
break;
}
if(end)
{
std::cout << "This way:\n";
while(id > 0)
{
q_mg.member(pt, id);
std::cout << "(" << pt.x << ", " << pt.y << ") ";
id = pt.pre;
}
q_mg.destroy();
return true;
}
else
return false;
}
由于是用链队实现的,输出路径反过来感觉有点麻烦懒得写了,感觉可以再定义一个栈,反向输出。