?? 123.txt
字號:
#include<iostream.h>
typedef int elemtype;
const int n=8;
const int e=10;
bool visited[n+1];
class link
{public:
elemtype data;
link *next;
};
class GRAPH
{
public:
link a[n+1];
void creatlink()
{int i,j,k;
link *s;
for(i=1;i<=n;i++)
{a[i].data=i;
a[i].next=NULL;
}
for(k=1;k<=e;k++)
{cout<<"請輸入一條邊";
cin>>i>>j;
s=new link;
s->data=j;
s->next=a[i].next;
a[i].next=s;
s=new link;
s->data=i;
s->next=a[j].next;
a[j].next=s; }
}
void dfs(int i)
{link *p;
int h[n],z=0;
cout<<a[i].data<<" ";
h[z++]=a[i].data;
visited[i]=true;
p=a[i].next;
while(z<n)
{
while(p!=NULL)
{while(!visited[p->data])
{cout<<a[p->data].data<<" ";
h[z++]=a[p->data].data;
visited[p->data]=true;
p=a[p->data].next;
}
p=p->next;
}
p=a[h[z-2]].next; }
}
void bfs(int i)
{int c[n+1];
int front,rear;
link *p;
front=rear=0;
cout<<a[i].data<<" ";
visited[i]=true;
rear++;c[rear]=i;
while(front<rear)
{front++;
i=c[front];
p=a[i].next;
while(p!=NULL)
{if(!visited[p->data])
{cout<<a[p->data].data<<" ";
visited[p->data]=true;
rear++;
c[rear]=p->data;
}
p=p->next; }
}
}
};
void main()
{
link *p;int i;
GRAPH G;
G.creatlink();
for(i=1;i<=n;i++)
{p=G.a[i].next;
cout<<G.a[i].data<<"->";
while(p->next!=NULL)
{cout<<p->data<<"->";
p=p->next;
}
cout<<p->data<<endl;
}
for(i=1;i<=n;i++)
visited[i]=false;
cout<<endl<<"請輸入深度優先搜索開始訪問的頂點";
cin>>i;
cout<<endl<<"從"<<i<<"出發的深度優先搜索遍歷序列為"<<endl;
G.dfs(i);
for(i=1;i<=n;i++)
visited[i]=false;
cout<<endl<<"請輸入廣度優先搜索開始訪問的頂點";
cin>>i;
cout<<"從"<<i<<"出發的廣度優先搜索遍歷序列為"<<endl;
G.bfs(i);
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -