四面楚歌 (简单bfs + 从外面开始搜索防止内存炸)

卡了很久,写得不是特别多吧, 四个方向的数组也不熟。

从 0 开始搜就行了

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<list>
#include<unordered_map>
using namespace std;
#define ff first
#define ss second
#define lowbit(x) (x&-x)
#define pf(a) printf("%d\n",a)
#define mem(x,y) memset(x,y,sizeof(x))
#define dbg(x) cout << #x << " = " << x << endl
#define rep(i,l,r) for(int i = l; i <= r; i++)
#define fep(i,a,b) for(int i=b; i>=a; --i)
typedef pair<int,int> PII;
typedef long long ll;
typedef unsigned long long ull;
int n, m;
const int N=1e4+100;
bool vis[N][N];
char a[N][N];
int cnt;

int dx[] = {-1,0,1,0};
int dy[] = {0,1,0,-1};

void bfs(int tx, int ty)
{
	vis[tx][ty] = true;
	queue<PII> q;
	q.push({tx,ty});
	while(q.size())
	{
		int x = q.front().ff;
		int y = q.front().ss;
		q.pop();
		rep(i,0,3)
		{
			int xx = x + dx[i], yy = y + dy[i];
			if(xx < 0 or xx > (n+1) or yy < 0 or yy > (m+1)) continue;
			if(!vis[xx][yy] and a[xx][yy]=='.') {
				vis[xx][yy] = true;
				q.push({xx,yy});
			}
			if(!vis[xx][yy] and a[xx][yy]=='0') {
				a[xx][yy] = '.';
				vis[xx][yy] = true;
				q.push({xx,yy});
				cnt++;
			}
		}
	}
}

void solve()
{

	cin >> n >> m;
	rep(i,0,n+1)
	{
		rep(j,0,m+1) a[i][j] = '.';
	}
	rep(i,1,n)
	{
		rep(j,1,m)
		{
			char tmp ;
			cin >> tmp;
			if(tmp!='.') a[i][j] = tmp;
		}
	}
	bfs(0,0);
	cout << cnt << endl;
	
}

int main()
{

	ios::sync_with_stdio(false);cin.tie(0);
		solve();
	return 0;
}
上一篇:DFS/BFS


下一篇:Open Judge 4001 - Catch That Cow - BFS