拯救OIBH总部
拯救OIBH总部
题目背景
oibh总部突然被水淹没了!现在需要你的救援……
题目描述
oibh被突来的洪水淹没了>.<还好oibh总部有在某些重要的地方起一些围墙,用*号表示,而一个封闭的*号区域洪水是进不去的……现在给出oibh的围墙建设图,问oibh总部没被淹到的重要区域(由"0"表示)有多少。
输入格式
第一行是两个数,x和y(x,y<=500)
第二行及以下是一个由*和0组成的x*y的图。
输出格式
输出没被水淹没的oibh总部的“0”的数量。
输入输出样例
输入 #1复制
样例输入1
4 5
00000
00*00
0*0*0
00*00
样例输入2
5 5
*****
*0*0*
**0**
*0*0*
*****
输出 #1复制
样例输出1
1
样例输出2
5
一个基本的染色问题
时间复杂度:O(nm)
算法: Flood Fil
#include<bits/stdc++.h>
using namespace std;
char g[505][505];
int vis[505][505],n,m;
const int dx[4]={-1,1,0,0};
const int dy[4]={0,0,-1,1};
void bfs(int x,int y)
{
vis[x][y]=1;
queue<int> q1,q2;
q1.push(x);
q2.push(y);
while(!q1.empty())
{
int nowx=q1.front(),nowy=q2.front();
q1.pop();q2.pop();
for(int i=0;i<4;i++)
{
int tx=nowx+dx[i];
int ty=nowy+dy[i];
if(tx>=0 and tx<=n+1 and ty>=0 and ty<=m+1 and !vis[tx][ty] and g[tx][ty]=='0')
{
vis[tx][ty]=1;
q1.push(tx);
q2.push(ty);
}
}
}
}
int main()
{
memset(g,'0',sizeof(g));
cin>>n>>m;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
cin>>g[i][j];
}
}
bfs(0,0);
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
if(g[i][j]=='0' and !vis[i][j])
{
ans++;
}
}
}
cout<<ans;
return 0;
}