生活随笔
收集整理的這篇文章主要介紹了
队列的其本应用_迷官问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
問題:
利用隊列的假出隊,實現(xiàn)迷官問題尋解。
要求:
0 墻 1 路, 尋找最短路, 如果有多條,輸出其中一條路。
main.c
#include <stdio.h>
#include <stdlib.h>#define M 5
int map[M+
2][M+
2];
int front =
0, rear =
0;
typedef struct Point_def{
int x;
int y;
int pre;
}Point;
Point q[(M+
2)*(M+
2)];
typedef struct direction_def{
int x;
int y;
}Direction;
Direction direct[
4] = {{-
1,
0}, {
0,
1}, {
1,
0}, {
0, -
1}
};
int isEmpty(){
return front==rear?
1:
0;
}
void initMap(){
int i, j;
for (i=
0; i<M+
2; i++)
for (j=
0; j<M+
2; j++){
if (i ==
0 || i == M+
1 || j ==
0 || j == M+
1){
map[i][j] =
0;
continue;}
scanf(
"%d", &
map[i][j]);}
}
void enQueue(Point p){q[rear++] = p;
}
Point deQueue(){
if (isEmpty())
exit(
1);
return q[front++];
}
void findPath(
int start_x,
int start_y,
int end_x,
int end_y){
int flag =
0;
int d;
int i, j;Point tmp_p1={start_x, start_y, -
1};Point tmp_p2;enQueue(tmp_p1);
while (!flag){tmp_p1 = deQueue();
map[tmp_p1.x][tmp_p1.y] = -
1;
for (d=
0; d<
4; d++){i = tmp_p1.x + direct[d].x;j = tmp_p1.y + direct[d].y;
if (
map[i][j] ==
1){tmp_p2.x = i; tmp_p2.y = j; tmp_p2.pre = front-
1;enQueue(tmp_p2);}
if (i == end_x && j == end_y){tmp_p2.x = i; tmp_p2.y = j; tmp_p2.pre = front-
1;enQueue(tmp_p2);flag =
1;
break;}}}
}
void printPath(){
int k = rear-
1;
while (k != -
1){
printf(
"(%d,%d)\n", q[k].x, q[k].y);k = q[k].pre;}
}
int main(){
int flag =
0;
int start_x =
1, start_y =
1;
int end_x =
5, end_y =
5;initMap();findPath(start_x, start_y, end_x, end_y);printPath();
return 0;
}
轉(zhuǎn)載于:https://www.cnblogs.com/laohaozi/p/8266613.html
總結(jié)
以上是生活随笔為你收集整理的队列的其本应用_迷官问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。