码迷,mamicode.com
首页 > 其他好文 > 详细

【P1141】01迷宫 {并查集}

时间:2019-01-20 00:59:43      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:his   clu   ||   name   space   nod   std   ++   source   

1、ptr -> x == (*ptr).x != *ptr.x

2、并查集寻父亲形式参数要!用!引!用!

#include <iostream>
#include <queue>
using namespace std;

class node{
    public:
        node():v(0),num(0),vis(0),x(0),y(0),pa(this){}
        bool v;
        int num;
        bool vis;
        int x;
        int y;
        node* pa;
};

int n,m;
int chx[4] = {0,1,0,-1};
int chy[4] = {-1,0,1,0};
node graph[1002][1002];

node* ancst(node& a){
    return ( a.pa == &a )? &a : ancst(*(a.pa));
}

bool ok(int x,int y,bool val){
    return (x < 1 || y < 1 || x > n || y > n || graph[x][y].vis || graph[x][y].v == val) ? 0 : 1;
}

void bfs(int x,int y){
    node* source = &(graph[x][y]); 
    if(source -> vis){
        source -> num = ancst(*source) -> num;
        return;
    }
    queue<node> q;
    q.push(*source);
    source -> vis = 1;
    int ans = 1;
    while(!q.empty()){
        node now = q.front();
        q.pop();
        for(int i = 0;i < 4;++i){
            int newx = now.x + chx[i];
            int newy = now.y + chy[i];
            if(ok(newx,newy,now.v)){
                q.push(graph[newx][newy]);
                graph[newx][newy].vis = 1;
                graph[newx][newy].pa = ancst(now);
                ++ans;
            }
        }
    }
    source -> num = ans;
    return;
}

int main(){
    cin >> n >> m;
    char now;
    for(int i = 1;i <= n;++i){
        for(int j = 1;j <= n;++j){
            cin >> now;
            graph[i][j].v = (now - ‘0‘);
            graph[i][j].x = i;
            graph[i][j].y = j;
        }
    }
    int x,y;
    for(int i = 0;i < m;++i){
        cin >> x >> y;
        bfs(x,y);
        cout << graph[x][y].num << endl;
    }
    return 0;
}

  

【P1141】01迷宫 {并查集}

标签:his   clu   ||   name   space   nod   std   ++   source   

原文地址:https://www.cnblogs.com/c-come/p/10293749.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!