【搜索】HDU1728:逃离迷宫

Description

  给定一个m × n (m行, n列)的迷宫,迷宫中有两个位置,gloria想从迷宫的一个位置走到另外一个位置,当然迷宫中有些地方是空地,gloria可以穿越,有些地方是障碍,她必须绕行,从迷宫的一个位置,只能走到与它相邻的4个位置中,当然在行走过程中,gloria不能走到迷宫外面去。令人头痛的是,gloria是个没什么方向感的人,因此,她在行走过程中,不能转太多弯了,否则她会晕倒的。我们假定给定的两个位置都是空地,初始时,gloria所面向的方向未定,她可以选择4个方向的任何一个出发,而不算成一次转弯。gloria能从一个位置走到另外一个位置吗?
 

Input

  第1行为一个整数t (1 ≤ t ≤ 100),表示测试数据的个数,接下来为t组测试数据,每组测试数据中, 
  第1行为两个整数m, n (1 ≤ m, n ≤ 100),分别表示迷宫的行数和列数,接下来m行,每行包括n个字符,其中字符'.'表示该位置为空地,字符'*'表示该位置为障碍,输入数据中只有这两种字符,每组测试数据的最后一行为5个整数k, x 1, y 1, x 2, y 2 (1 ≤ k ≤ 10, 1 ≤ x 1, x 2 ≤ n, 1 ≤ y 1, y 2 ≤ m),其中k表示gloria最多能转的弯数,(x 1, y 1), (x 2, y 2)表示两个位置,其中x 1,x 2对应列,y 1, y 2对应行。 
 

Output

  每组测试数据对应为一行,若gloria能从一个位置走到另外一个位置,输出“yes”,否则输出“no”。
 

Sample Input

2
5 5
...**
*.**.
.....
.....
*....
1 1 1 1 3
5 5
...**
*.**.
.....
.....
*....
2 1 1 1 3
 

Sample Output

no
yes
 
 
注意:这里行和列是互换的,wa了好久才发现
 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <queue>
 5 #include <algorithm>
 6 #include <cmath>
 7 using namespace std;
 8 char str[105][105];
 9 int n,m;
10 int k,x1,x2,y3,y2;
11 int ds[4][2]={-1,0,1,0,0,-1,0,1};
12 int vis[105][105];
13 bool flag;
14 struct node
15 {
16     int x,y,cnt;
17 };
18 
19 void bfs()
20 {
21     node tt;
22     tt.x=x1;
23     tt.y=y3;
24     tt.cnt=-1;
25     vis[x1][y3]=1;
26     queue<node> q;
27     q.push(tt);
28     while(q.empty()==0)
29     {
30         node now;
31         now=q.front();
32         q.pop();
33         if(now.x==x2&&now.y==y2&&now.cnt<=k)
34             flag=true;
35         for(int i=0;i<4;i++)
36         {
37             node next1;
38             next1.x=now.x+ds[i][0];
39             next1.y=now.y+ds[i][1];
40             while(next1.x>=1&&next1.x<=n&&next1.y>=1&&next1.y<=m&&str[next1.x][next1.y]!='*')
41             {
42                 if(vis[next1.x][next1.y]==0)
43                 {
44                     next1.cnt=now.cnt+1;
45                     vis[next1.x][next1.y]=1;
46                     q.push(next1);
47                 }
48                 node next2;
49                 next2.x=next1.x+ds[i][0];
50                 next2.y=next1.y+ds[i][1];
51                 next1=next2;
52             }
53         }
54     }
55 }
56 int main()
57 {
58     int T;
59     cin>> T;
60     while(T--)
61     {
62         scanf("%d%d",&n,&m);
63         for(int i=1;i<=n;i++)
64         {
65             for(int j=1;j<=m;j++)
66             {
67                 scanf(" %c",&str[i][j]);
68             }
69         }
70         memset(vis,0,sizeof(vis));
71         scanf("%d%d%d%d%d",&k,&y3,&x1,&y2,&x2);
72         flag=false;
73         bfs();
74         if(flag==true)
75             cout << "yes" << endl;
76         else
77             cout << "no" << endl;
78     }
79 
80     return 0;
81 }
View Code
 
原文地址:https://www.cnblogs.com/SoulSecret/p/8440648.html