题目要求:
给定矩形长宽,及起始坐标,求所有与起始坐标有关联的X形成图形的周长。
有关联是指所有利用九宫格联系起来的格子
思路:
1、从起始坐标开始,将他周围八个格子里是X的标为Y,并从被标为Y的格子开始同样的搜索//注意,别忘了标记初始位置,我就是忘了标初始位置,WA了好多次
2、遍历数组,找出等于Y的格子,再计算它周围有几个不等于Y的格子,有几个,周长就加几//画下图,很容易懂的
另外,记得初始化数组
实现:
#include <stdio.h>
//#include <stdlib.h>
#include <string.h>
int A,B,X,Y;
char grid[21][21];
void search(int x,int y){
if(grid[x-1][y]=='X') {grid[x-1][y]='Y';search(x-1,y);}
if(grid[x+1][y]=='X') {grid[x+1][y]='Y';search(x+1,y);}
if(grid[x][y-1]=='X') {grid[x][y-1]='Y';search(x,y-1);}
if(grid[x][y+1]=='X') {grid[x][y+1]='Y';search(x,y+1);}
if(grid[x-1][y+1]=='X') {grid[x-1][y+1]='Y';search(x-1,y+1);}
if(grid[x+1][y+1]=='X') {grid[x+1][y+1]='Y';search(x+1,y+1);}
if(grid[x-1][y-1]=='X') {grid[x-1][y-1]='Y';search(x-1,y-1);}
if(grid[x+1][y-1]=='X') {grid[x+1][y-1]='Y';search(x+1,y-1);}
}
int main(){
memset(grid,'.',sizeof(char)*21*21);
scanf("%d %d %d %d",&A,&B,&X,&Y);
int i,j;
int tms=0;
//getchar();
while(A&&B&&X&&Y){
getchar();
for(i=1;i<=A;i++){
for(j=1;j<=B;j++)
grid[i][j]=getchar();
getchar();
}
grid[X][Y]='Y';
search(X,Y);
for(i=1;i<=A;i++)
for(j=1;j<=B;j++){
if(grid[i][j]!='Y') continue;
if(grid[i][j+1]!='Y') tms++;
if(grid[i][j-1]!='Y') tms++;
if(grid[i-1][j]!='Y') tms++;
if(grid[i+1][j]!='Y') tms++;
}
printf("%d\n",tms);
tms=0;
memset(grid,'.',sizeof(char)*21*21);
scanf("%d %d %d %d",&A,&B,&X,&Y);
}
return 0;
}