一下程序使用队列,通过广度优先搜索算法。得到迷宫的最优解。目前只得到最短不数,还无法正确获取每一步的坐标
日后完善。
-
#include<stdio.h>
-
-
-
typedef struct point {
-
int x;
-
int y;
-
int level;
-
}Point;
-
-
Point Queue[100];
-
int head;
-
int tail;
-
Point data[100];
-
int count = 0;
-
-
Point data1[100];
-
int count1 = 0;
-
-
-
void Init_Queue()
-
{
-
int i;
-
for (i = 0; i < 100; i++) {
-
Queue[i].x = 0;
-
Queue[i].y = 0;
-
Queue[i].level = 0;
-
}
-
head = 0;
-
tail = 0;
-
}
-
-
int IsEmpty(void) {
-
if (head == tail)
-
return 1;
-
-
return 0;
-
}
-
-
void Add_Queue_Tail(Point p)
-
{
-
-
Queue[tail] = p;
-
-
tail++;
-
-
if (tail >= 100)
-
tail = 0;
-
-
-
}
-
-
Point Del_Queue_Head() {
-
Point p;
-
-
p = Queue[head];
-
Queue[head].x = 0;
-
Queue[head].y = 0;
-
-
if (count < 100) {
-
data[count] = p;
-
count++;
-
}
-
else {
-
printf("erro\n");
-
}
-
-
head++;
-
if (head >= 100)
-
head = 0;
-
-
return p;
-
}
-
-
void Disply_Queue() {
-
int i;
-
-
if (IsEmpty()) {
-
printf("Queue is empty\n");
-
return ;
-
}
-
-
printf("\n");
-
if (head < tail) {
-
for (i = head; i < tail; i++) {
-
printf("#%d (%d,%d) ", i, Queue[i].x, Queue[i].y);
-
}
-
}
-
else {
-
for (i = head; i < 100; i++) {
-
printf("#%d (%d,%d) ", i, Queue[i].x, Queue[i].y);
-
}
-
for (i = 0; i < tail; i++) {
-
printf("#%d (%d,%d) ", i, Queue[i].x, Queue[i].y);
-
}
-
}
-
printf("\n");
-
-
}
-
-
-
int buff[5][5] = {
-
0, 1, 0, 0, 0,
-
0, 0, 0, 1, 0,
-
1, 0, 0, 0, 0,
-
0, 1, 0, 1, 0,
-
0, 0, 0, 1, 0
-
};
-
-
int visit[5][5];
-
-
-
//四个方向
-
int dir[4][2] = {
-
{ 0, 1 },{ 1, 0 },
-
{ 0, -1 },{ -1, 0 }
-
};
-
-
void Init_Visit(void)
-
{
-
int i, j;
-
for (i = 0; i < 5; i++) {
-
for (j = 0; j < 5; j++) {
-
visit[i][j] = 0;
-
}
-
}
-
}
-
-
int Test(void)
-
{
-
int i, x, y ,sum = 0,flag = 0;
-
int Cur_level = 1;
-
Point p, result;
-
-
result.x = 4;
-
result.y = 4;
-
-
-
Init_Visit();
-
Init_Queue();
-
p.x = 0;
-
p.y = 0;
-
p.level = 1;
-
-
Add_Queue_Tail(p);
-
-
visit[p.x][p.y] = 1;
-
-
while (!IsEmpty()) {
-
p = Del_Queue_Head();
-
-
flag = 0;
-
for (i = 0; i < 4; i++) {
-
x = p.x + dir[i][0];
-
y = p.y + dir[i][1];
-
Cur_level = p.level;
-
if (x < 0 || x>4 || y < 0 || y>4) {
-
if ((i == 3) && (flag == 0)) {
-
if (count1 < 100) {
-
data1[count1] = p;
-
count1++;
-
}
-
else {
-
printf("erro\n");
-
}
-
}
-
continue;
-
}
-
if (x == 4 && y == 4) {
-
-
printf("find it level =%d \n", p.level);
-
return 1;
-
}
-
-
if ((buff[x][y] == 0) && (visit[x][y] != 1)) {
-
p.x = x;
-
p.y = y;
-
p.level = Cur_level +1;
-
Add_Queue_Tail(p);
-
visit[x][y] = 1;
-
flag = 1;
-
}
-
-
if ((i == 3 )&&(flag == 0)) {
-
if (count1 < 100) {
-
data1[count1] = p;
-
count1++;
-
}
-
else {
-
printf("erro\n");
-
}
-
}
-
-
}
-
-
}
-
printf("fail\n");
-
return 0;
-
}
-
-
void main(void)
-
{
-
int i;
-
Test();
-
-
-
for (i = 0; i < count; i++)
-
{
-
printf(" (%d,%d) ", data[i].x, data[i].y);
-
}
-
printf("\n");
-
for (i = 0; i < count1; i++)
-
{
-
printf(" (%d,%d) ", data1[i].x, data1[i].y);
-
}
-
printf("\n");
-
-
printf("end\n");
-
while (1);
-
}
阅读(938) | 评论(0) | 转发(0) |