题目
题目描述:sun所在学校每年都要举行电脑节,今年电脑节有一个新的趣味比赛项目叫做闯迷宫。sun的室友在帮电脑节设计迷宫,所以室友就请sun帮忙计算下走出迷宫的最少步数。知道了最少步数就可以辅助控制比赛难度以及去掉一些没有路径到达终点的map。比赛规则是:从原点(0,0)开始走到终点(n-1,n-1),只能上下左右4个方向走,只能在给定的矩阵里走。输入:输入有多组数据。每组数据输入n(0<=100),然后输入n*n的01矩阵,0代表该格子没有障碍,为1表示有障碍物。注意:如果输入中的原点和终点为1则这个迷宫是不可达的。输出:对每组输入输出该迷宫的最短步数,若不能到达则输出-1。样例输入:20 10 050 0 0 0 01 0 1 0 10 0 0 0 00 1 1 1 01 0 1 0 0样例输出:28
思路
- 简单的bfs题目,二维方向上对广度优先搜索的考察
- 注意剪枝法的使用,防止重复访问
AC代码
#include#include #include struct node{ int x, y, step;}; struct queue{ struct node data[10010]; int front, rear, count;}; int dire[4][2] = { {0, 1}, {0, -1}, {1, 0}, {-1, 0}};int maze[110][110]; void enqueue(struct queue *Q, struct node p);struct node dequeue(struct queue *Q);int bfs(int n); int main(){ int n, i, j; while (scanf("%d", &n) != EOF) { // 接受迷宫数据 for (i = 0; i < n; i ++) { for (j = 0; j < n; j ++) { scanf("%d", &maze[i][j]); } } // 处理异常情况 if (maze[0][0]) { printf("-1\n"); }else if (maze[n - 1][n - 1]) { printf("-1\n"); }else { printf("%d\n", bfs(n)); } } return 0;} void enqueue(struct queue *Q, struct node p){ Q->data[Q->rear] = p; Q->rear += 1; Q->count += 1;} struct node dequeue(struct queue *Q){ struct node p; p = Q->data[Q->front]; Q->front += 1; Q->count -= 1; return p;} int bfs(int n){ int i, tx, ty, tt; struct node s, u, q; // 初始化队列 struct queue *Q = (struct queue*)malloc(sizeof(struct queue)); Q->front = Q->rear = Q->count = 0; // 首元素入队列 s.x = s.y = s.step = 0; maze[0][0] = 1; enqueue(Q, s); while (Q->count > 0) { u = dequeue(Q); if (u.x == n - 1 && u.y == n - 1) { return u.step; } for (i = 0; i < 4; i ++) { tx = u.x + dire[i][0]; ty = u.y + dire[i][1]; tt = u.step + 1; if (tx >= 0 && ty >= 0 && tx < n && ty < n && maze[tx][ty] == 0) { maze[tx][ty] = 1; q.x = tx; q.y = ty; q.step = tt; enqueue(Q, q); } } } return -1;}/************************************************************** Problem: 1335 User: wangzhengyi Language: C Result: Accepted Time:150 ms Memory:3304 kb****************************************************************/