Problem 最大黑区域
Accepted: 585 Total Submit: 1044Time Limit: 1000ms Memony Limit: 32768KB
Description
二值图像是由黑白两种像素组成的矩形点阵,图像识别的一个操作是求出图像中最大黑区域的面积。请设计一个程序完成二值图像的这个操作。黑区域由黑像素组成,一个黑区域中的每个像素至少与该区域中的另一个像素相邻,规定一个像素仅与其上、下、左、右的像素相邻。两个不同的黑区域没有相邻的像素。一个黑区域的面积是其所包含的像素的个数。
Input
输入由多个测试例组成。每个测试例的第一行含两个整数n和m, (1 <=n,m<=100), 分别表示二值图像的行数与列数,后面紧跟着n行,每行含m个整数0或1,其中第i行表示图像的第i行的m个像素,0表示白像素,1表示黑像素。同一行的相邻两个整数之间用一个空格隔开,两个测试例之间用一个空行隔开,最后一个测试例之后隔一个空行,再接的一行含有两个整数0,标志输入的结束。
Ouput
每个测试例对应一行输出,含一个整数,表示相应的图像中最大黑区域的面积。
Sample Input
5 6
0 1 1 0 0 1
1 1 0 1 0 1
0 1 0 0 1 0
0 0 0 1 1 1
1 0 1 1 1 0
0 0
0 1 1 0 0 1
1 1 0 1 0 1
0 1 0 0 1 0
0 0 0 1 1 1
1 0 1 1 1 0
0 0
Sample Output
7
思路分析:这道题就是找是1的上下左右有没有1然后继续一直找。。。直到1的上下左右没有1为止,所以我们先来分4个方向 即dx【】 dy【 】 然后用一个flag标记有没有走过,看到这里就是一道简单的深搜。至于怎么实现一直找的办法看下面代码的bfs方法
import java.util.Scanner;
public class P_1221 {
static int dx[]= {0,0,-1,1};
static int dy[]= {1,-1,0,0};
static int max = 0;
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int n = in.nextInt();
int m = in.nextInt();
if(n==0&&m==0){
break;
}
int black[][] = new int[n][m];
int flag[][] = new int[n][m];
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
black[i][j] = in.nextInt();
flag[i][j] = 0;
}
}
int mm = 0;
for(int i = 0;i<n;i++){
for(int j = 0;j<m;j++){
if(black[i][j]==1){
max = 0;
bfs(i,j, black, flag);
if(max>mm)
mm = max;
}
}
}
System.out.println(mm);
}
}
public static void bfs(int x1,int y1,int[][] black,int[][] flag) {
if(x1>=0&&y1>=0&&x1<black.length&&y1<black[0].length&&black[x1][y1]==1&&flag[x1][y1]==0){
flag[x1][y1] = 1;
max++;
for(int i = 0;i<4;i++){
int x = x1+dx[i];
int y = y1+dy[i];
bfs(x,y,black,flag);
}
}
}
}