北邮OJ[278]
最近遇到两题关于地图深搜的题,一道是杭电[1010]狗狗找门,自己写不出来,看了别人的答案。今天遇到这题,试着用深搜思路写了出来,记录下来。
《图像识别》,一个点的相邻的8个点中,只要数值与该点相差不超过给定值,就认为是一个色域,求色域的个数。
1,涉及地图,且有走动的题,多会定义方向,注意二维数组的定义方式:
int direction[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
2,注意地图坐标的边界条件
3,二维数组的传参问题,二维数组要至少规定列才可以穿参
代码(被学长说代码风格进步很大,嗨森! 简直是一个程序员女友养成记,冷笑):
#include <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
int direction[8][2] = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};
int DFS(int val, int x, int y, int map[][100], int d, int row, int col){
map[x][y] = -1;
for(int i = 0; i < 8; i++){
int newx = x + direction[i][0];
int newy = y + direction[i][1];
if(newx > -1 && newx < row && newy > -1 && newy < col
&& map[newx][newy] > -1
&& abs(map[newx][newy] - val) <= d){
//cout << "val:" << val << ": " << map[newx][newy] << "x: " <<newx << "y: " <<newy<< endl;
DFS(map[newx][newy],
newx, newy, map, d, row, col);
}
}
return 0;
}
int main(){
int n;
cin >> n;
while(n--){
int row, col, d;
cin >> row >> col >> d;
int map[100][100] = {-1};
for(int i = 0; i < row; i ++){
for(int j = 0; j < col; j++){
scanf(" %d", &map[i][j]);
}
}
int num = 0;
for(int i = 0; i < row; i ++){
for(int j = 0; j < col; j++){
if(map[i][j] != -1){
DFS(map[i][j], i, j, map, d, row, col);
num ++;
//cout << "num: "<< num << endl;
}
}
}
cout << num << endl;
}
}