题意:给出一个矩阵,对于每个0统计其上下左右有几个方向是1,该点的对应值就是几。计算矩阵中所有0的对应值之和。
题解:先跑一次纵向,求出每个点在纵向上的对应值之和。再跑一次横向,求出每个点在横向上的对应值之和。总体复杂度为 O(2*n^2)
代码如下:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
using namespace std;
const int maxn = 1000+10;
typedef long long LL;
const int INF = 1e9+10;
int a[maxn][maxn];
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;++i)
for(int j=0;j<m;++j)
scanf("%d",&a[i][j]);
int ans=0;
for(int i=0;i<n;++i)
{
int cnt=0,flag=0;
for(int j=0;j<m;++j)
{
if(a[i][j]==0&&(!flag))
cnt++;
else if(a[i][j]==1)
{
ans+=cnt;
cnt=0;
flag=1;
}
else if(a[i][j]==0&&flag)
{
ans++;
cnt++;
}
}
}
for(int j=0;j<m;++j)
{
int cnt=0,flag=0;
for(int i=0;i<n;++i)
{
if(a[i][j]==0&&(!flag))
cnt++;
else if(a[i][j]==1)
{
ans+=cnt;
cnt=0;
flag=1;
}
else if(a[i][j]==0&&flag)
{
ans++;
cnt++;
}
}
}
printf("%d\n",ans);
}
return 0;
}