【bfs】BZOJ1102- [POI2007]山峯和山谷Grz

最後刷個水,睡覺去。Bless All!node

【題目大意】c++

給定一個地圖,爲FGD想要旅行的區域,地圖被分爲n*n的網格,每一個格子(i,j) 的高度w(i,j)是給定的。
若兩個格子有公共頂點,那麼他們就是相鄰的格子。(因此與(i,j)相鄰的格子有(i−1, j−1),(i−1,j),(i−1,j+1),(i,j−1),(i,j+1),(i+1,j−1),(i+1,j),(i+1,j+1))。
咱們定義一個格子的集合S爲山峯(山谷)當且僅當:
1.S的全部格子都有相同的高度。
2.S的全部格子都聯通
3.對於s屬於S,與s相鄰的s’不屬於S。都有ws > ws’(山峯),或者ws < ws’(山谷)。
你的任務是,對於給定的地圖,求出山峯和山谷的數量,若是全部格子都有相同的高度,那麼整個地圖便是山峯,又是山谷。less

【思路】spa

普通的bfs。判斷是不是山峯和山谷的方法就是若是周圍和它們不等高,那麼就記下比它們高仍是比它們低。最後若是統一高,就是山谷;統一低,就是山峯。code

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 const int MAXN=1000+5;
 4 int w[MAXN][MAXN],vis[MAXN][MAXN];
 5 int peak,valley,higher,lower,n;
 6 int dx[8]={1,1,1,-1,-1,-1,0,0};
 7 int dy[8]={0,1,-1,0,1,-1,1,-1};
 8 struct node
 9 {
10     int x,y;
11 };
12 queue<node> que;
13 
14 void init()
15 {
16     peak=valley=0;
17     scanf("%d",&n);
18     for (int i=1;i<=n;i++)
19         for (int j=1;j<=n;j++) scanf("%d",&w[i][j]);
20 }
21 
22 void bfs(int x,int y)
23 {
24     lower=higher=0;
25     while (!que.empty()) que.pop();
26     que.push((node){x,y});
27     vis[x][y]=1;
28     while (!que.empty())
29     {
30         int hx=que.front().x,hy=que.front().y;
31         que.pop();
32         for (int i=0;i<8;i++)
33         {
34             int xx=hx+dx[i],yy=hy+dy[i];
35             if (xx<=0 || xx>n || yy<=0 || yy>n) continue;
36             if (w[xx][yy]==w[hx][hy] && !vis[xx][yy])
37             {
38                 que.push((node){xx,yy});
39                 vis[xx][yy]=1;
40             }
41             else
42             {
43                 if (w[xx][yy]>w[hx][hy]) higher++;
44                     else if (w[xx][yy]<w[hx][hy]) lower++;
45             }
46         } 
47     } 
48     if (higher==0 && lower!=0) peak++;
49     if (lower==0 && higher!=0) valley++; 
50 }
51 
52 void solve()
53 {
54     memset(vis,0,sizeof(vis));
55     for (int i=1;i<=n;i++)
56         for (int j=1;j<=n;j++)
57             if (!vis[i][j]) bfs(i,j);
58     if (!peak && !valley) peak=valley=1;
59     printf("%d %d\n",peak,valley);
60 }
61 
62 int main()
63 {
64     init();
65     solve();
66     return 0;
67 } 
相關文章
相關標籤/搜索