king's trouble I


Time Limit: 1000 MS    Memory Limit: 131072 K


   


Description




Long time ago, a king occupied a vast territory.
Now there is a problem that he worried that he did not know how much of the perimeter of his territory.
Can you help him?


For simplicity, we use a matrix to represent the territory as follows:
0 0 0 0 0
0 1 0 1 0
1 1 0 1 0
0 1 1 0 0
0 0 1 0 0

Every single number in the matrix represents a piece of land, which is a 1*1 square
1 represents that this land has been occupied
0 represents not

Obviously the perimeter of all ocupied lands is 20

Input



The first line of the input contains a single integer t (1≤t≤5) — the number of cases.
For each case
The first line has two integers N and M representing the length and width of the matrix
Then M lines follows to describe the matrix
1≤N,M≤400



Output



For each case output the perimeter of all ocupied lands

Sample Input



1
5 5
0 0 0 0 0
0 1 0 1 0
1 1 0 1 0
0 1 1 0 0
0 0 1 0 0

Sample Output




20

思路:

思路很简单,一种是在外层找到0然后看它的四周有几个1,另一种是找到1看他的四周有几个0,

在1周围找0代码如下

#include<stdio.h>
#include<string.h>
const int maxn=500;
int pic[maxn][maxn];
int m,n,idx[maxn][maxn];
int d[4][2]= {0,1,0,-1,1,0,-1,0};
int dfs(int r,int c)
{
       int we,ni;
       int sum=0;
        for(int i=0; i<4; i++)
        {
            we=r+d[i][0];
            ni=c+d[i][1];
            if(pic[we][ni]==0)
            {
               sum++;
            }
        }
        return sum;
    }
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&m,&n);
        int s1=0;memset(pic,0,sizeof(pic));
        for(int i=1; i<=m; i++)
        {
            for(int j=1; j<=n; j++)
            {
                scanf("%d",&pic[i][j]);
            }
        }

        int sum=0;
        for(int i=1; i<=m; i++)
        {
            for(int j=1; j<=n; j++)
            {
                if(pic[i][j]==1)
                {
                    sum+=dfs(i,j);
                }
            }
        }
        printf("%d\n",sum);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值