无向图的基本操作
#include<iostream>
using namespace std;
#define MAXSIZE 100
bool visited[MAXSIZE] = { false };
class Graph {
private:
char vertex[MAXSIZE];
int edge[MAXSIZE][MAXSIZE]={0};
int VertexNum, EdgeNum;
public:
Graph(char a[], int n, int e);
~Graph();
void DFtraverse(int v);
void BFtraverse(int v);
void Print();
};
//构造函数
Graph::Graph(char a[], int n, int e) {
int i, j;//顶点下标
int k;//边数
VertexNum = n;
EdgeNum = e;
for (int i = 0; i < VertexNum; i++) {
vertex[i] = a[i];
}
for (int i = 0; i < VertexNum; i++) {
for (int k = 0; k < VertexNum; k++) {
edge[i][k] = 0;
}
}
for (int k = 0; k < EdgeNum; k++) {
cin >> i >> j;
edge[i][j] = 1;
edge[j][i] = 1;
}
}
Graph::~Graph() {
}
//深度优先遍历
void Graph::DFtraverse(int v) {
cout << vertex[v] << " ";
visited[v] = true;
for (int i = 0; i < VertexNum; i++) {
if (edge[v][i] == 1 && visited[i] != true) {
DFtraverse(i);
}
}
}
//广度优先遍历 (队列)
void Graph::BFtraverse(int v) {
int w, j;
int Q[MAXSIZE];
//初始顶点都没有被访问
for (int i = 0; i < VertexNum; i++) {
visited[i] = false;
}
int front = -1, rear = -1;
cout << vertex[v] << " ";
visited[v] = true;
Q[++rear] = v;
while (front!=rear)
{
w = Q[++front];
for (int j = 0; j < VertexNum; j++) {
if (edge[w][j] == 1 && visited[j] != true) {
cout << vertex[j] << " ";
visited[j] = true;
Q[++rear] = j;
}
}
}
}
void Graph::Print() {
for (int i = 0; i < VertexNum; i++)
{
for (int j = 0; j < VertexNum; j++)
{
cout << edge[i][j] << " ";
}
cout << endl;
}
}
int main(){
char ch[] = { 'A','B','C','D','E' };
Graph MG(ch,5,6);//在构造函数中传入初始默认参数{5个顶点6个边}
cout << endl << "深度优先遍历是:" << endl;
MG.DFtraverse(0);//从顶点0出发
cout << endl << "广度优先遍历是:" << endl;
MG.BFtraverse(0);
cout << endl;
MG.Print();
return 0;
}
事件绑定
<body>
<input type="button" value="点我" onclick="on()">
<input type="button" value="再点我" id="btn">
<script>
function on(){
alert("success");
}
document.getElementById("btn").onclick=function (){
alert("xixi");
}
</script>
</body>