# [GIS算法] DEM – 种子搜索法替换面属性 – C

【题目】种子搜索法替换面属性

【DEM文件】

``````8 10
2 2 3 4 6 7 7 3 2 2
5 6 7 4 5 1 2 5 7 9
1 2 2 1 1 1 1 7 9 0
3 2 1 1 1 1 6 9 9 7
3 2 1 1 1 1 1 3 7 8
4 5 6 7 1 1 2 3 5 8
1 0 0 9 8 8 9 2 4 7
3 2 2 1 6 9 0 1 5 0
4 3 5
``````

【代码】

``````#include<stdio.h>
#include<stdlib.h>

typedef struct{
double x0,y0; //左下角点的坐标值
int dx,dy; //栅格单元大小
int ycount,xcount; //行列号
double **M; //矩阵
}DEM;

DEM* CreateDEM();
int InitDEM(FILE *fp, DEM *pDEM);
void PrintDEM(DEM dem);

double GetValue(DEM dem, int row, int col) {
return dem.M[row][col];
}
// 说明：八连通区域
void Reclass(DEM *pDEM, int row, int col, double attr, double toAttr) {
int i,j;
int x,y;

// 该位置不等于attr，退出
if ( pDEM->M[row][col]!=attr ) return;
// 超出范围，退出
if (row<0 && row>pDEM->xcount && col<0 && col>pDEM->ycount) return ;
// 扩散
pDEM->M[row][col] = toAttr;
for (i=-1; i<=1; i++) {
for (j=-1; j<=1; j++) {
x = row+i;
y = col+j;
Reclass(pDEM, x, y, attr, toAttr);
}
}
}

int main() {
FILE *fp;
DEM *pDEM;
int row,col;
double toAttr;

fp = fopen("2018-7.txt", "r");
printf("读取dem中...\n读取成功！\n");
pDEM = CreateDEM(fp);
InitDEM(fp, pDEM);
PrintDEM(*pDEM);
printf("\n");

fscanf(fp, "%d%d%lf", &row, &col, &toAttr);
printf("种子点(%d,%d)->颜色%lf （坐标描述规则：行、列）", row, col, toAttr);

Reclass(pDEM, row, col, GetValue(*pDEM, row, col) ,toAttr);
printf("\n重分类结果...\n");
PrintDEM(*pDEM);

fclose(fp);
return 0;
}

DEM* CreateDEM(FILE *fp) {
DEM *p;
int i;
p = (DEM *)malloc(sizeof(DEM)); if (!p) exit(0);
fscanf(fp, "%d%d", &p->xcount, &p->ycount);
p->M = (double **)malloc(sizeof(double *) * p->xcount); if (!p->M) exit(0);
for (i=0; i<p->xcount; i++) {
p->M[i] = (double *)malloc(sizeof(double)* p->ycount);
if (!p->M[i]) exit(0);
}
return p;
}
int InitDEM(FILE *fp, DEM *pDEM) {
int i,j;

for (i=0; i<pDEM->xcount; i++) {
for (j=0; j<pDEM->ycount; j++) {
fscanf(fp, "%lf", &pDEM->M[i][j]);
}
}
return 1;
}
void PrintDEM(DEM dem) {
int i,j;

for (i=0; i<dem.xcount; i++) {
for (j=0; j<dem.ycount; j++) {
printf("%lf\t", dem.M[i][j]);
}
printf("\n");
}
}

``````