hihocoder #1319 : 区域周长

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/MM_GS/article/details/78028189

#1319 : 区域周长


题目链接

时间限制: 10000ms
单点时限: 1000ms
内存限制: 256MB

描述

给定一个包含 N × M 个单位正方形的矩阵,矩阵中每个正方形上都写有一个数字。

对于两个单位正方形 a 和 b ,如果 a 和 b 有一条共同的边,并且它们的数字相等,那么 a 和 b 是相连的。

相连还具有传递性,如果 a 和 b 相连,b 和 c 相连,那么 a 和 c 也相连。

给定一个单位正方形 ss 和与 s 相连的所有单位正方形会组成一个区域 R 。小Hi想知道 R 的周长是多少?

输入

第一行包含4个整数 N , M ,x 和 y , N 和 M 是矩阵的大小, x 和 y 是给定的单位正方形 s 的坐标。(1 ≤ N , M ≤ 100, 0 ≤ x < N , 0 ≤ y < M )

以下是一个 N × M 的矩阵 AAij 表示相应的正方形上的数字。(0 ≤ Aij ≤ 100)

输出

输出一个整数表示 R 的周长。

样例输入
6 5 2 1
0 0 1 2 2
3 1 1 3 7
4 3 1 3 7
4 3 0 3 2
4 3 3 0 1
4 5 5 5 5
样例输出
10

#include <iostream>
#include <stdio.h>
using namespace std;
int a[105][105];
int n,m;
bool flag[105][105];
int ans=0;
int dx[4]={0,1,-1,0},dy[4]={1,0,0,-1};
void dfs(int x,int y){
	flag[x][y]=1;
	for (int i=0;i<4;i++){
		int nx=dx[i]+x,ny=dy[i]+y;
		if (0<=nx && nx<n && 0<=ny && ny<m && a[nx][ny]==a[x][y]){
			if (flag[nx][ny]!=1){
				if (a[nx][ny]==a[x][y])	 dfs(nx,ny);
				else
					ans++;
			}
		}
		else
			ans++;		
	}
	return;
}

int main()
{
	int x,y;
	cin>>n>>m>>x>>y;
	for (int i=0;i<n;i++){
		for (int j=0;j<m;j++){
			scanf ("%d",&a[i][j]);
		}
	}
	dfs(x,y);
	cout<<ans<<endl;
	return 0;	
} 



猜你喜欢

转载自blog.csdn.net/MM_GS/article/details/78028189