hihocoder8 [Offer收割]编程练习赛8 拆字游戏

bfs

//http://www.cnblogs.com/IMGavin/
#include <iostream>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <vector>
#include <map>
#include <stack>
#include <set>
#include <bitset>
#include <algorithm>
using namespace std;

typedef long long LL;
#define gets(A) fgets(A, 1e8, stdin)
const int INF = 0x3F3F3F3F, N = 600, MOD = 1003;

const double EPS = 1e-6;

int n, m, ti;
char str[N][N];
int mp[N][N];

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

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

void bfs(int r, int c){
	int r1 = r, r2 = r, c1 = c, c2 = c;
	ti++;
	queue<node> q;
	q.push(node(r, c));
	mp[r][c] = ti;
	while(!q.empty()){

		node u = q.front();
		q.pop();
		for(int i = 0; i < 4; i++){
			int  x = u.x + dir[i][0];
			int  y = u.y + dir[i][1];
			if(x >= 0 && x < n && y >= 0 && y < m){
				if(mp[x][y] == 0&& str[x][y] == '1'){
					r1 = min(r1, x);
					r2 = max(r2, x);
					c1 = min(c1, y);
					c2 = max(c2, y);

					mp[x][y] = ti;
					q.push(node(x, y));
				}
			}
		}
	}
	printf("%d %d\n", r2 - r1  + 1, c2 - c1 + 1);
	for(int i = r1; i <= r2; i++){
		for(int j = c1 ; j <= c2; j++){
			if(mp[i][j] == ti ){
				printf("1");
			}else{

				printf("0");
			}
		}
		printf("\n");

	}
}

int main(){
	while(cin >> n >> m){
		ti = 0;
		for(int i = 0; i < n; i++){
			scanf("%s", str[i]);
		}
		memset(mp, 0, sizeof(mp));
		for(int j = 0; j < m; j++){
			for(int i = 0; i < n; i++){
				if(mp[i][j] == 0 && str[i][j] == '1'){
					bfs(i, j);
				}
			}
		}

	}
	return 0;
}

  

posted @ 2017-03-05 16:08  vwirtveurit  阅读(227)  评论(0编辑  收藏  举报