Problem C. 圖像識別
題目描述
在圖像識別中,我們經常需要分析特定圖像中的一些特徵,而其中很重要的一點就是識別出圖像的多個區域。在這個問題中,我們將給定一幅N x M的圖像,其中每個1 x 1的點都用一個[0,255]的值來表示他的RGB顏色。如果兩個相鄰的像素點顏色差不超過D,我們就認爲這兩個像素點屬於同一個區域。對於一個像素點(x,y) ,以下這8個點(如果存在)是與它相鄰的:(x-1, y-1),(x-1,y),(x-1,y+1),(x,y-1),(x,y+1),(x+1,y-1),(x+1,y),(x+1,y+1)。
你的任務是寫一個程序,分辨出給定圖像中一共被分爲多少個區域。
輸入格式
輸入數據包含多組測試數據。
輸入的第一行是一個整數T(T<=100),表示測試數據的組數。
每組測試數據的第一行是三個整數N,M,D(1<=N,M<=100, 0<=D<=255),意義如上所述。
接下來N行,每行M個整數,表示給定圖像的每個像素點顏色。
輸出格式
對於每組測試數據輸出一行,即圖像中的區域數量。
輸入樣例
2
3 3 0
1 1 1
0 1 0
0 1 0
3 4 1
10 11 12 13
9 8 7 6
2 3 4 5
輸出樣例
3
1
//ʹÓÃDFS ÕÒÁ¬Í¨·ÖÁ¿Êý
//°Ñ²îÖµ<=D£¨Í¬ÊôÓÚÒ»¸öÇøÓò£©£¬³éÏóΪ¿É´ï£¨Á¬Í¨£©£¨Ö¸Õë´æÔÚ£©
#include <iostream>
#include <cstdio>
#define MAXSIZE 120
using namespace std;
int t,n,m,d;
int color[MAXSIZE][MAXSIZE];
bool visited[MAXSIZE][MAXSIZE];
int abs(int x){
return x>=0?x:-x;
}
void DFS(int x,int y,int preColor){
if ( (0<=x&&x<=n-1&&0<=y&&y<=m-1) && visited[x][y]==false && abs(preColor-color[x][y])<=d ){//²»Ô½½ç£¬Î´·ÃÎʹý£¬ÇÒÖ¸Õë´æÔÚ£¨Á¬Í¨£©
//visit
visited[x][y]=true;
DFS(x-1,y-1,color[x][y]);
DFS(x-1,y,color[x][y]);
DFS(x,y-1,color[x][y]);
DFS(x+1,y+1,color[x][y]);
DFS(x+1,y,color[x][y]);
DFS(x,y+1,color[x][y]);
DFS(x+1,y-1,color[x][y]);
DFS(x-1,y+1,color[x][y]);
}
}
int main(){
scanf("%d",&t);
int count;
while (t--){
//input && initiate
scanf("%d%d%d",&n,&m,&d);
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
scanf("%d",&color[i][j]);/*bug*/
visited[i][j]=false;
}
}
count=0;
//DFS
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
if (visited[i][j]==false){
count++;
DFS(i,j,color[i][j]);
}
}
}
//output
printf("%d\n",count);
}
return true;
}