题意:理解为搜索一幅图中‘X’相连组成图形的周长(从输入中给出的点开始搜索),相连的定义则是在该点周围8个方向为‘x’。较为简单的dfs题....
Input
The input will contain one or more grids. Each grid is preceded by a line containing the number of rows and columns in the grid and the row and column of the mouse click. All numbers are in the range 1-20. The rows of the grid follow, starting on the next line,
consisting of '.' and 'X' characters.
The end of the input is indicated by a line containing four zeros. The numbers on any one line are separated by blanks. The grid rows contain no blanks.
The end of the input is indicated by a line containing four zeros. The numbers on any one line are separated by blanks. The grid rows contain no blanks.
Output
For each grid in the input, the output contains a single line with the perimeter of the specified object.
Sample Input
2 2 2 2 XX XX 6 4 2 3 .XXX .XXX .XXX ...X ..X. X... 5 6 1 3 .XXXX. X....X ..XX.X .X...X ..XXX. 7 7 2 6 XXXXXXX XX...XX X..X..X X..X... X..X..X X.....X XXXXXXX 7 7 4 4 XXXXXXX XX...XX X..X..X X..X... X..X..X X.....X XXXXXXX 0 0 0 0
思路:dfs,不过这次不是求有多少‘x’与之相连,求周长。先假设某个‘x’上下左右都没有‘x’,它的周长为4,然后四个方向上找到一个‘x’,周长--。(可能没说清楚,不过就是这么回事)
代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
using namespace std;
int visit[25][25];
char map[25][25];
int n,m,sum=0;
int d[8][2]= {{1,0},{1,-1},{0,-1},{-1,-1},
{-1,0},{-1,1},{0,1},{1,1}};//搜索时的8个方向
bool inside(int x,int y)//搜索时判断是否在图内
{
if(x<0||x>=n||y<0||y>=m)
return false;
return true;
}
void dfs(int x,int y)
{
if(visit[x][y]==0&&map[x][y]=='X'&&inside(x,y))
{
visit[x][y]=1;
int p=4;//默认该点周长为4
if(map[x-1][y]=='X') --p;
if(map[x][y-1]=='X') --p;
if(map[x+1][y]=='X') --p;
if(map[x][y+1]=='X') --p;
sum+=p;
for(int i=0; i<8; i++)//8个方向深搜
{
dfs(x+d[i][0],y+d[i][1]);
}
}
}
int main()
{
int i,j,x,y;
while(scanf("%d%d%d%d",&n,&m,&x,&y))//x,y为指定点的坐标
{
if(x+y+m+n==0)
break;
memset(visit,0,sizeof(visit));
memset(map,0,sizeof(map));
for(i=0; i<n; i++)
for(j=0; j<m; j++)
{
cin>>map[i][j];
}
sum=0;
dfs(x-1,y-1);//我是从map[0][0]开始记录的
printf("%d\n",sum);
}
return 0;
}