Red and Black---hdu1312(dfs)

时间:2023-03-08 17:55:37

2015-04-07http://acm.hdu.edu.cn/showproblem.php?pid=1312

Sample Input
6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
11 9
.#.........
.#.#######.
.#.#.....#.
.#.#.###.#.
.#.#..@#.#.
.#.#####.#.
.#.......#.
.#########.
...........
11 6
..#..#..#..
..#..#..#..
..#..#..###
..#..#..#@.
..#..#..#..
..#..#..#..
7 7
..#.#..
..#.#..
###.###
...@...
###.###
..#.#..
..#.#..
0 0

Sample Output
45
59
6
13
////////////////////////////////////////
题意:
.代表黑色瓷砖;
#代表红色瓷砖;
@是起始位置;
求的是从起始位置开始所能走的黑色的块的个数,不能跳过红色;

用递归的方法一次找到上下左右的所有有关的黑色瓷砖;

代码如下:

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std; #define maxn 105 char G[maxn][maxn];
int m, n; int f(int x, int y)
{ if(x< || x>=m || y< || y>=n)//如果当前位置超出矩阵范围,则返回0
return ; else if(G[x][y] == '#')//否则如果当前位置是白色方格,则返回0
return ; else//否则
{
//将走过的瓷砖做标记;
G[x][y] = '#';
//递归处理
return +f(x-, y)+f(x+, y)+f(x, y-)+f(x, y+);
}
} int main()
{ int i, j, x, y; cin >> m >> n; for(i=; i<m; i++)
for(j=; j<n; j++)
{
cin >> G[i][j]; if(G[i][j] == '@')
x=i, y=j;
} int ans = f(x, y); cout << ans <<endl; return ;
}
 #include<iostream>
#include<string.h>
#define N 25
using namespace std;
char maps[N][N];
int m,n,ans;
int dir[][]={ {,},{-,},{,},{,-} }; void dfs(int x,int y)
{
int i;
if(x>=m||x<||y>=n||y<)
return ;
if(maps[x][y]=='#')
return ;
else
{
maps[x][y]='#';
ans++;
for(i=;i<;i++)
{
dfs(x+dir[i][],y+dir[i][]);
}
}
} int main()
{
int i,x,y,j;
while(scanf("%d%d",&n,&m),m+n)
{
ans=;
memset(maps,,sizeof(maps));
for(i=;i<m;i++)
{
for(j=;j<n;j++)
{
cin>>maps[i][j];
if(maps[i][j]=='@')
{
x=i,y=j;
}
}
}
dfs(x,y);
printf("%d\n",ans);
}
return ;
}