POJ 3984 迷宫问题

题目大意:中文

题目链接

注释代码:

/*                                                  
 * Problem ID : POJ 3984 迷宫问题
 * Author     : Lirx.t.Una                                                  
 * Language   : C                                 
 * Run Time   : 0 ms                                                  
 * Run Memory : 132 KB                                                  
*/ 

#include <stdio.h>

typedef	struct { char	x, y; } Pos;

char	maze[5][5];//迷宫
char	vis[5][5];//BFS中检测一个点是否被访问过

Pos		q[5 * 5 + 1];//BFS的队列
char	pre[5 * 5];//用来记录每个点的父结点,记录内容为q中结点的下标

//表示向量(dx, dy),上下左右四种走法
int		dx[4] = { -1, 1, 0, 0 };
int		dy[4] = { 0, 0, -1, 1 };

//由于每次直走一步,因此广度优先搜索下第一个解必定是最优解(因为步数最少)

void
print(int x) {//递归打印出完整的路线
	//即打印从头到尾每个点的坐标
	
	if ( !x ) {
		
		puts("(0, 0)");
		return ;
	}
	
	print(pre[x]);
	printf("(%d, %d)\n", q[x].x, q[x].y);
}

int
main() {
	
	int		i, j;//计数变量
	int		head, tail;//队列的头尾
	
	int		x, y;//移动前的坐标
	int		xx, yy;//移动后的坐标
	
	for ( i = 0; i < 5; i++ )
		for ( j = 0; j < 5; j++ )
			scanf("%d", &maze[i][j]);

		//BFS
		
		vis[0][0] = 1;
		head = 0;
		tail = 1;
		
		while ( head < tail ) {
			
			x = q[head].x;
			y = q[head].y;
			
			for ( i = 0; i < 4; i++ ) {
				
				xx = x + dx[i];
				yy = y + dy[i];
				
				if ( xx >= 0 && xx < 5 && yy >= 0 && yy < 5 &&//没走出迷宫外面
					!maze[xx][yy] && !vis[xx][yy] ) {//不是障碍物且没有访问过
					
					//push
					q[tail].x = xx;
					q[tail].y = yy;
					
					pre[tail] = head;//记录前驱
					
					if ( 4 == xx && 4 == y ) {//搜索到目标
						
						print(tail);
						return 0;
					}
					
					vis[xx][yy] = 1;
					tail++;
				}
			}
			
			head++;//pop
		}
		
		return 0;
}
无注释代码:

#include <stdio.h>

typedef	struct { char	x, y; } Pos;

char	maze[5][5];
char	vis[5][5];

Pos		q[5 * 5 + 1];
char	pre[5 * 5];

int		dx[4] = { -1, 1, 0, 0 };
int		dy[4] = { 0, 0, -1, 1 };

void
print(int x) {

	if ( !x ) {
		
		puts("(0, 0)");
		return ;
	}

	print(pre[x]);
	printf("(%d, %d)\n", q[x].x, q[x].y);
}

int
main() {

	int		i, j;
	int		head, tail;

	int		x, y;
	int		xx, yy;

	for ( i = 0; i < 5; i++ )
		for ( j = 0; j < 5; j++ )
			scanf("%d", &maze[i][j]);

	vis[0][0] = 1;
	head = 0;
	tail = 1;

	while ( head < tail ) {

		x = q[head].x;
		y = q[head].y;

		for ( i = 0; i < 4; i++ ) {
		
			xx = x + dx[i];
			yy = y + dy[i];

			if ( xx >= 0 && xx < 5 && yy >= 0 && yy < 5 &&
				 !maze[xx][yy] && !vis[xx][yy] ) {
			
				q[tail].x = xx;
				q[tail].y = yy;

				pre[tail] = head;

				if ( 4 == xx && 4 == y ) {
				
					print(tail);
					return 0;
				}

				vis[xx][yy] = 1;
				tail++;
			}
		}

		head++;
	}

	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值