HDU - 1241 (DFS)(BFS)

15 篇文章 0 订阅
14 篇文章 0 订阅

题目链接:HDU 1241

思路: 用BFS DFS。

AC代码:

 

DFS

#include<iostream>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 205;
const int INF = (1 << 31) - 1;
char maze[maxn][maxn];
int vis[maxn][maxn]; 
int n, m;
int X[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int Y[8] = {0, 0, 1, -1, -1, 1, 1, -1};

struct node{
	int x, y;
};
bool check(node now){
	if(now.x < 1 || now.x > n || now.y < 1 || now.y > m || maze[now.x][now.y] == '*'){
		return 0;
	}
	return 1;
}
void DFS(node s){
	vis[s.x][s.y] = 1;
	node next;
	for(int i = 0; i < 8; i ++){
		next.x = s.x + X[i];
		next.y = s.y + Y[i];
		if( check(next) && !vis[next.x][next.y] ){
			vis[next.x][next.y] = 1;
			DFS(next);
		}
	}
}
int main(){
	while(cin >> n >> m && n + m){
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m;j ++){
				cin >> maze[i][j];
			}
		}
		memset(vis, 0, sizeof(vis));
		int ans = 0;
		node temp;
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m; j++){
				if( !vis[i][j] && maze[i][j] == '@'){
					ans ++;
					temp.x = i;
					temp.y = j;
					DFS(temp);
				}
			}
		}
		cout << ans << endl;
	}
	return 0;
}

BFS:

#include<iostream>
#include<cstring>
#include<string.h>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
const int maxn = 205;
const int INF = (1 << 31) - 1;
char maze[maxn][maxn];
int vis[maxn][maxn]; 
int n, m;
int X[8] = {1, -1, 0, 0, 1, 1, -1, -1};
int Y[8] = {0, 0, 1, -1, -1, 1, 1, -1};

struct node{
	int x, y;
};
bool check(node now){
	if(now.x < 1 || now.x > n || now.y < 1 || now.y > m || maze[now.x][now.y] == '*'){
		return 0;
	}
	return 1;
}
int BFS(node s){
	queue<node> q;
	q.push(s);
	vis[s.x][s.y] = 1;
	node front, next;
	while(!q.empty()){
		front = q.front();
		q.pop();
		for(int i = 0; i < 8; i++){
			next.x = front.x + X[i];
			next.y = front.y + Y[i];
			if(check(next) && vis[next.x][next.y] == 0){
				vis[next.x][next.y] = 1;
				q.push(next); 
			}
		}
	}
}
int main(){
	while(cin >> n >> m && n + m){
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m;j ++){
				cin >> maze[i][j];
			}
		}
		memset(vis, 0, sizeof(vis));
		int ans = 0;
		node temp;
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= m; j++){
				if( !vis[i][j] && maze[i][j] == '@'){
					ans ++;
					temp.x = i;
					temp.y = j;
					BFS(temp);
				}
			}
		}
		cout << ans << endl;
	}
	return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值