北大ACM1979 - Red and Black (广度优先搜索)

 

1.1      算法分析

这是一道很简单的广度优先搜索问题,我们以原始位置开始向四个方向搜索,如果是黑色的地砖,则将地砖标记为已经搜索过,然后搜索该黑色砖的四个临近地砖;如果该地砖是红色的或者搜素过的,则不再对该地砖进行搜索了。

1.2      代码

/*
 *
 * Introduction : ACM of pku
 * ID : 1979
 * alg : BFS
 * Author : Gykimo
 * Date : 20130105
 * 
 */

#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <stdio.h>

using namespace std;

const char VISITED = '!';		//0x21
const char RED = '#';				//0x23
const char BLK = '.';				//0x2E
const char INI = '@';				//0x40

char tiles[20][20];
int w,h;
int init_row, init_col;
int num = 0;

void dfs(int row, int col){
	if(tiles[row][col] < BLK || row < 0 || col < 0 || row >= h || col >= w)
		return;

	num++;
	tiles[row][col] = VISITED;

	dfs(row, col -1);
	dfs(row - 1, col);
	dfs(row, col + 1);
	dfs(row + 1, col);
}

void get_init_position(){
	bool getted = false;
	
	for(int i=0; i<h; i++){
		if(getted)
			break;
		
		for(int j=0; j<w; j++){
			if(tiles[i][j] == INI){
				init_row = i;
				init_col = j;
				getted = true;
				break;
			}
		}
	}
}

void readLine(){
	char s[20] = {0};
	
	while(1){
		scanf("%d%d", &w, &h);
		if(w==0 && h==0)
			break;

		for(int i=0; i<h; i++){
			scanf("%s", s);
			memcpy(&tiles[i][0], s, w);
		}

		num = 0;
		get_init_position();
		dfs(init_row, init_col);
		printf("%d\n", num);
	}
}

int main(){
	readLine();
	return 0;
}


 

1.3      运行结果

 696K 16MS 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值