Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- struct node{
- int val;
- node* next;
- };
- void mlist(struct node** tab,int n){ //wypisz
- for(int i = 0; i < n; i++){
- cout << "A[" << i << "] =";
- struct node* p = tab[i];
- while(p)
- {
- cout << " " << p->val;
- p = p->next;
- }
- cout << endl;
- }
- }
- int dfs(node** tab,int start,bool visited[]){
- visited[start] = true;
- int ile = 0;
- cout<<start;
- struct node* p = tab[start];
- int pom = 0;
- if(p == NULL){
- ile=ile+1;
- }
- while(p){
- if(visited[p->val] == false) {
- //cout<<endl<<"p->val"<<p->val<<"pom:"<<pom<<endl;
- ile += dfs(tab,p->val,visited);
- }
- //ile = ile+pom;
- p=p->next;
- }
- return ile+1;
- }
- bool canGoAnywhere(int n,int m,int trains[][2]){
- if(m<n-1) {
- cout<<"cannot";
- return false;
- }
- struct node** A = new node * [n];
- bool visited[n] = {false};
- for(int i = 0; i<n; i++) A[i] = NULL;
- for(int i = 0;i<m;i++){
- if(A[trains[i][0]] == NULL){
- struct node* p = new node;
- p->val=trains[i][1];
- p->next=NULL;
- A[trains[i][0]]=p;
- }
- else{
- struct node* q = A[trains[i][0]];
- while(q->next){
- q=q->next;
- }
- struct node* p = new node;
- p->val=trains[i][1];
- p->next=NULL;
- q->next=p;
- }
- if(A[trains[i][1]]==NULL){
- struct node* p = new node;
- p->val=trains[i][0];
- p->next=NULL;
- A[trains[i][1]]=p;
- }
- else{
- struct node* q = A[trains[i][1]];
- while(q->next){
- q=q->next;
- }
- struct node* p = new node;
- p->val=trains[i][0];
- p->next=NULL;
- q->next=p;
- }
- }
- struct node* p = A[0];
- mlist(A,n);
- int res=dfs(A,0,visited);
- if(res==n){
- return true;
- }
- //cout<<endl<<"res: "<<dfs(A,0,visited)<<endl;
- else{
- return false;
- }
- //mlist(A,n);
- }
- /* run this program using the console pauser or add your own getch, system("pause") or input loop */
- int main(int argc, char** argv) {
- int trains[][2]={{0,1},{1,2},{2,0},{3,4}};
- int n = 5;
- int m = 4;
- //cout<<trains[1][0];
- cout<<canGoAnywhere(n,m,trains);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement