题目:http://101.200.220.237/contest/49/problem/288/
sunshine16被困了
故事发生在很久很久以前,在山的那边有一群黄精灵,他们很喜欢捉弄人。有一天,sunshine16迷路走到了黄精灵布置的迷宫中,0代表路,1代表墙,sunshine16被困在迷宫中,只可以上下左右走,不可以斜着走。
这个迷宫错综复杂,sunshine16有封闭恐惧症,所以他迫切的想要找到出口,如果不能很快的找到出口的话,他会很害怕, 同学们快来帮帮他吧。
sunshine16的初始位置在第一行第一列,他现在要尽快的跑到出口(最后一行最后一列)
输入包含多组数据 先输入一个正整数n,接下来是一个n*n的矩阵。(保证存在至少一条逃跑路线)(1<=n<=20)
输出其中最短路径的长度。
复制4 0 1 1 1 0 1 0 0 0 1 0 1 0 0 0 07复制3 0 0 0 0 1 0 0 1 05
bfs题目,代码如下:
#include <stdio.h> #include<iostream> #include<set> #include<algorithm> #include<cstdio> #include<cstring> #include<string.h> #include<queue> using namespace std; int a[100001]; int point[30][30]; struct Node { int x, y; int num; int visit; int go; int ww, aa, ss, dd; Node *w, *a, *s, *d; }node[30][30]; int main() { int k, n; Node y; int sum; int i, j; while (cin >> n ) { for (i = 1; i <= 30; i++) for (j = 1; j <= 30; j++) { node[i][j].visit = 0; node[i][j].num = i*30+j; node[i][j].aa = 0; node[i][j].ss = 0; node[i][j].ww = 0; node[i][j].dd = 0; node[i][j].go = 0; node[i][j].y = i; node[i][j].x = j; } for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) { cin >> point[i][j]; if (point[i][j] == 0) node[i][j].go = 1; } for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) { if (i - 1 >= 1) { node[i][j].w = &node[i - 1][j]; node[i][j].ww = 1; } if (j - 1 >= 1) { node[i][j].a = &node[i][j - 1]; node[i][j].aa = 1; } if (i + 1 <= n) { node[i][j].s = &node[i + 1][j]; node[i][j].ss = 1; } if (j + 1 <= n) { node[i][j].d = &node[i][j + 1]; node[i][j].dd = 1; } } memset(a, 0, sizeof(a)); queue<Node>x;//建立名为x的队列 x.push(node[1][1]);//在队列后加入n // a[n] = 0; while (x.size() != 0)//队列大小不为0 { y = x.front();//y取队列首位 x.pop();//去掉队列首位 y.visit = 1; if (y.x == n && y.y == n) break; if (y.aa == 1 && ((y.a)->visit) == 0 &&((y.a)->go==1)) { x.push(*(y.a)); a[(y.a)->num] = 1 + a[y.num]; (y.a)->visit = 1; } if (y.ss == 1 && ((y.s)->visit) == 0 && ((y.s)->go == 1)) { x.push(*(y.s)); a[(y.s)->num] = 1 + a[y.num]; (y.s)->visit = 1; } if (y.dd == 1 && ((y.d)->visit) == 0 && ((y.d)->go == 1)) { x.push(*(y.d)); a[(y.d)->num] = 1 + a[y.num]; (y.d)->visit = 1; } if (y.ww == 1 && ((y.w)->visit) == 0 && ((y.w)->go == 1)) { x.push(*(y.w)); a[(y.w)->num] = 1 + a[y.num]; (y.w)->visit = 1; } } cout << a[y.num]+1 << endl; } return 0; }