Codeforces Round #301 (Div. 2) B. School Marks

其实是很水的一道bfs题,昨晚比赛的时候没看清题意,漏了一个条件。

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 #include<cmath>
 5 #include<algorithm>
 6 #include<set>
 7 #include<map>
 8 #include<queue>
 9 #include<stack>
10 #include<string>
11 #include<vector>
12 #define maxn
13 #define INF 1000000000
14 using namespace std;
15 int vist[510][510];
16 char str[510][510];
17 int dirx[]={-1,0,1,0};
18 int diry[]={0,1,0,-1};
19 int m,n,stx,sty,edx,edy;
20 int judge(int x,int y)
21 {
22     if(x>=0&&x<n&&y>=0&&y<m)
23         return 1;
24     return 0;
25 }
26 int bfs()
27 {
28     queue<int> q;
29     stx--;
30     sty--;edx--;edy--;
31     int num=stx*m+sty;
32     q.push(num);
33     //vist[stx][sty]--;就改的这个地方,因为起点和终点有可能相同
34     while(!q.empty())
35     {
36         num=q.front();
37         //printf("%d==
",num);
38         q.pop();
39         int xx=num/m;
40         int yy=num%m;
41 
42         for(int i=0;i<4;i++)
43         {
44             int newx=xx+dirx[i];
45             int newy=yy+diry[i];
46             if(newx==edx&&newy==edy&&vist[newx][newy]==0)
47                 return 1;
48             if(judge(newx,newy)&&vist[newx][newy]>0)
49             {
50                 q.push(newx*m+newy);
51                 vist[newx][newy]--;
52             }
53         }
54     }
55     //printf("==
");
56     return 0;
57 
58 }
59 int main()
60 {
61     scanf("%d %d",&n,&m);
62     for(int i=0;i<n;i++)
63         scanf("%s",str[i]);
64     scanf("%d %d",&stx,&sty);
65     scanf("%d %d",&edx,&edy);
66     for(int i=0;i<n;i++)
67     {
68         for(int j=0;j<m;j++)
69         {
70             if(str[i][j]=='X')
71                 vist[i][j]=0;
72             else
73                 vist[i][j]=1;
74         }
75     }
76     if(bfs())
77         printf("YES
");
78     else
79         printf("NO
");
80     return 0;
81 }
原文地址:https://www.cnblogs.com/tsw123/p/4470387.html