HDU-1312(red and black)

其实,以前是不知道有些小范围内的BFS是可以用递归来写的。

写起来也是非常的方便的,也不知道多大的范围用递归写就会超栈,

但是这种思路还是值得提倡的。一会在用BFS写一下,好久没有写过了。

贴出代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

char G[22][22];

int H, W;

int startX, startY;

int fun(int x, int y)
{
	if (x < 0 || x >= H || y < 0 || y >= W)
	{
		return 0;
	}
	if (G[x][y] == '#')
	{
		return 0;
	}
	if (G[x][y] == '.' || G[x][y] == '@')
	{
		G[x][y] = '#';
		return 1 + fun(x - 1, y) + fun(x + 1, y) + 
			fun(x, y - 1) + fun(x, y + 1);
	}
}
	


int main()
{
	while (scanf("%d%d", &W, &H) != EOF)
	{
		if (H == 0 && W == 0)
		{
			break;
		}
		for (int i = 0; i < H; i++)
		{
			getchar();
			for (int j = 0; j < W; j++)
			{
				scanf("%c", &G[i][j]);
				if (G[i][j] == '@')
				{
					startX = i;
					startY = j;
				}
			}
		}
		int ans = fun(startX, startY);
		printf("%d\n", ans);
	}
//	system("pause");
	return 0;
}


DFS的写法...居然WA了两次是因为没有加N=0,M=0的条件,我哭;

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <queue>

using namespace std;

int N, M;

char G[55][55];

int startX, startY;

int vis[55][55];

int d_x[4] = {1, -1, 0, 0};

int d_y[4] = {0, 0, 1, -1};

struct node
{
	int x, y;
	node()
	{
		x = 0;
		y = 0;
	}
};

bool judge(int x, int y)
{
	if (x < 0 || x >= N || y < 0 || y >= M || G[x][y] == '#')
	{
		return 0;
	}
	return 1;
}

int BFS()
{
	int sum = 1;
	queue <node> Q;
	node n;
	n.x = startX;
	n.y = startY;
	vis[startX][startY] = 1;
	Q.push(n);
	while (!Q.empty())
	{
		n = Q.front();
		Q.pop();
		for (int i = 0; i < 4; i++)
		{
			int x = n.x + d_x[i];
			int y = n.y + d_y[i];
			if (judge(x, y) && !vis[x][y])
			{
				vis[x][y] = 1;
//				cout << "x = " << x << " ";
//				cout << "y = " << y << endl;
				sum++;
				node t;
				t.x = x;
				t.y = y;
				Q.push(t);
			}
		}
	}
	return sum;
	
}

int main()
{
	while (scanf("%d%d", &M, &N) != EOF)
	{
		if (N == 0 && M == 0)
		{
			break;
		}
		memset(vis, 0, sizeof(vis));
		for (int i = 0; i < N; i++)
		{
			scanf("%s", G[i]);
			for (int j = 0; j < M; j++)
			{
				if (G[i][j] == '@')
				{
					startX = i;
					startY = j;
				}
			}
		}
		int ans = BFS();
		printf("%d\n", ans);
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值