1. 程式人生 > >鄰接表陣列實現

鄰接表陣列實現

#include<stdio.h>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;


int head[400010];

struct node{
    int n_v;
    int next;
}edge[400010];

int bfs(int n){


    queue<int>q;
    int vis[200010];
    memset(vis,0,sizeof(vis));
    int s = 1,e = n;
    int vs;
    q.push(1);
    vis[1] = 1;
    while(!q.empty()){

        s = q.front();
        q.pop();
        for (int t = head[s];t!=-1;t = edge[t].next){

            vs = edge[t].n_v;
            if(vs == e)return 1;
            if(vis[vs] == 0){
                q.push(vs);
                vis[vs] = 1;
            }

        }


    }



    return 0;

}

int main(){

    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        int u ,v;
        int k = 0;
        memset(head,-1,sizeof(head));
        for (int i = 0;i<m;i++){

            scanf("%d%d",&u,&v);
            edge[k].n_v = v;
            edge[k].next = head[u];
            head[u] = k++;
            edge[k].n_v = u;
            edge[k].next = head[v];
            head[v] = k++;


        }
        if(bfs(n))puts("POSSIBLE");
        else puts("IMPOSSIBLE");
    }

}