1. 程式人生 > 其它 >D. 1.綠紋龍的森林遊記 [ Problem 4398 ] [ Discussion ]

D. 1.綠紋龍的森林遊記 [ Problem 4398 ] [ Discussion ]

技術標籤:題目BFS

D. 1.綠紋龍的森林遊記 [ Problem 4398 ] [ Discussion ]
Description
暑假來了,綠紋龍很高興。於是飄飄乎就來到了森林一日遊。可是他卻看到了很不和諧的一幕,一群獵人在森林裡圍捕小動物。森林可以看做是一個10*10的方格,如下圖所示,1表示獵人,0表示小動物。

已知獵人保持不動,而小動物可以往上下左右任意方向逃脫(當然不能撞上獵人)。小動物可以逃出森林。但上圖背景色被標紅的那部分小動物將永遠無法逃脫獵人的魔爪。
在這裡插入圖片描述

Input
一個10*10的矩陣,描述森林中獵人和小動物分佈的情況。保證每個點要麼為獵人,要麼為小動物。

Output
一個整數,表示不能逃脫獵人魔爪的小動物數量。

Samples
Input Copy
0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0
0 0 0 0 1 0 0 1 0 0
0 0 0 0 0 1 0 0 1 0
0 0 1 0 0 0 1 0 1 0
0 1 0 1 0 1 0 0 1 0
0 1 0 0 1 1 0 1 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0
Output
15

思路
從四條邊每一個邊的每一個點開始
這都是出口
除了出口是1

那麼只需要從出口模擬接下來走的路線都可以了

走過的就不用再走了

#include<bits/stdc++.h>
#include<stdio.h>
#include<string.h>
using
namespace std; typedef long long ll; typedef pair<int,int> PII; ll read(){ll res = 0, ch, flag = 0;if((ch = getchar()) == '-')flag = 1;else if(ch >= '0' && ch <= '9')res = ch - '0';while((ch = getchar()) >= '0' && ch <= '9' )res = res * 10 + ch - '0';return flag ? -res : res;
} const int maxn =1e6+199 ; ll sum=0,maxa=-1; ll n,m,k,w,ans=0,cnt=0; ll a[300][300]; ll b[300][300]; ll dis[4][2]={{1,0},{-1,0},{0,1},{0,-1}}; ll mod=1e9+7; struct node{ int x,y; }st,en; queue<node>p; void bfs(int x,int y) //作用 遍歷下一個位置並標記1 如果是1那麼continue { st.x=x; st.y=y; p.push(st); while(!p.empty()) { st=p.front(); p.pop(); a[st.x][st.y]=1; for(int i=0;i<=3;i++) { en.x=st.x+dis[i][0]; en.y=st.y+dis[i][1]; if(en.x<1||en.y<1||en.x>10||en.y>10||a[en.x][en.y]) continue; a[en.x][en.y]=1; p.push(en); } } } int main() { for(int i=1;i<=10;i++) { for(int j=1;j<=10;j++) cin>>a[i][j]; } for(int i=1;i<=10;i++) { if(!a[1][i]) //如果是出口就沿著出口找 能活下來的標記 bfs(1,i); if(!a[i][1]) bfs(i,1); if(!a[i][10]) bfs(i,10); if(!a[10][i]) bfs(10,i); } for(int i=1;i<=10;i++) { for(int j=1;j<=10;j++) if(a[i][j]==0) cnt++; } cout<<cnt; return 0; }