dfs POJ-1979

版权声明:博客作者为blue bear,严禁他人在未经作者同意下进行商用转载 https://blog.csdn.net/weixin_44354699/article/details/87733002

题目链接

[https://vjudge.net/contest/279018#problem/I]
[http://poj.org/problem?id=1979]

题面

There is a rectangular room, covered with square tiles. Each tile is colored either red or black. A man is standing on a black tile. From a tile, he can move to one of four adjacent tiles. But he can’t move on red tiles, he can move only on black tiles.
Write a program to count the number of black tiles which he can reach by repeating the moves described above.

Input

The input consists of multiple data sets. A data set starts with a line containing two positive integers W and H; W and H are the numbers of tiles in the x- and y- directions, respectively. W and H are not more than 20.

There are H more lines in the data set, each of which includes W characters. Each character represents the color of a tile as follows.

‘.’ - a black tile
‘#’ - a red tile
‘@’ - a man on a black tile(appears exactly once in a data set)
The end of the input is indicated by a line consisting of two zeros.
Output
For each data set, your program should output a line which contains the number of tiles he can reach from the initial tile (including itself).

Sample Input

6 9
…#.
…#





#@…#
.#…#.
11 9
.#…
.#.#######.
.#.#…#.
.#.#.###.#.
.#.#…@#.#.
.#.#####.#.
.#…#.
.#########.

11 6
…#…#…#…
…#…#…#…
…#…#…###
…#…#…#@.
…#…#…#…
…#…#…#…
7 7
…#.#…
…#.#…
###.###
…@…
###.###
…#.#…
…#.#…
0 0

Sample Output

45
59
6
13

题意

给个W列和H行然后给H*W的字符
字符含义如下:
’.’ - 黑色瓷砖
’#’ - 红色瓷砖
’@’- 黑色瓷砖上的男人
人可以往前后左右走,但是只能走黑色的瓷砖,问一共能走多少块黑色瓷砖。
很普通一道深搜的题,别忘了他一开始站着的也是黑色的瓷砖。

分析

从‘@’那里开始搜,如果不是‘#’(红色瓷砖)就答案+1然后把它改成‘#’防止再次搜索到。
别忘了处理越界情况,4个方向的转移可以开一个数组来实现,省去打4个方向的代码。(讲给我这个新手自己听的) 我这里的判断是!=’#'所以会把‘@’那里也算进去不会漏一块。

代码

#include <stdio.h>
int n,m,sum;
char  a[105][105];
int d[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
void dfs(int i,int j){
	if(i<0 || j<0 || i>=m || j>=n) return;
	if(a[i][j]!='#'){
		a[i][j]='#';
		sum++;
		for(int k=0;k<4;k++){
			dfs(i+d[k][0],j+d[k][1]);
		}
	}
} 
int main(){
	int i,j,pos_i,pos_j;
	while(scanf("%d %d",&n,&m)!=EOF){
		if(m==0 && n==0) return 0;
		sum=0;
		for(i=0;i<m;i++){
			scanf("%s",a[i]);
		}	
		for(i=0;i<m;i++){
			for(j=0;j<n;j++){
				if(a[i][j]=='@') pos_i=i,pos_j=j;
			}
		}
		dfs(pos_i,pos_j);
		printf("%d\n",sum); 
	}
	
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_44354699/article/details/87733002