洛谷P1162 填涂颜色(bfs)

https://www.luogu.org/problem/P1162

思路:将图从1-n存起来,外面一圈用0填充,然后从(0,0)开始搜

// luogu-judger-enable-o2
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <vector>
#include <cstring>
#include <map>
#define mem(a) memset(a,0,sizeof(a))
using namespace std;
typedef long long lll;
const int maxn = 200005;
const lll INF = 0x3f3f3f3f3f;
int dir[8][2]= {0,1,0,-1,1,0,-1,0,-1,-1,1,-1,-1,1,1,1};
int dir2[4][2]= {0,1,0,-1,1,0,-1,0};
bool flag;
int a[35][35],b[35][35],n;
struct node{
    int x,y;
    node(){};
    node(int xx,int yy):x(xx),y(yy){};
};

void bfs(int x,int y)
{
    queue<node>q;
    q.push(node(0,0));//(0,0)一定是0
    while(!q.empty()){
        int fx = q.front().x,fy = q.front().y;
        q.pop();
        b[fx][fy] = 3;//将圈外的0标记为3
        for(int i=0;i<4;i++)
        {
            int ex = fx + dir2[i][0],ey = fy + dir2[i][1];
            if(ex < 0 || ex > n+1 || ey < 0 || ey > n + 1 || b[ex][ey] == 1 || b[ex][ey] == 3)
                continue;
            q.push(node(ex,ey));
        }
    }
}
int main()
{
    cin >> n;
    for(int i = 1; i <= n; i++)
    for(int j = 1; j <= n; j++){
        cin >> a[i][j];
        if(a[i][j] == 0) b[i][j] = 2;
        else b[i][j] = 1;
    }
    bfs(0,0);
    for(int i = 1; i <= n; i++){
        for(int j =1; j <= n; j++){
            if(b[i][j] == 3 ) cout << "0";
        else
                cout << b[i][j];
            if(j < n) cout << " ";
            else cout << endl;
        }
    }
    return 0;
}

 

posted on 2019-08-03 10:44  一只小毛球  阅读(171)  评论(0编辑  收藏  举报

导航