图的相关操作(构建、遍历)

图的构建(邻接矩阵):

include

define MAXVEX 100

define INFINITY 65535

typedef struct
{
VertexType vexs[MAXVEX];
EdgeType arc[MAXVEX][MAXVEX];
int numVertexes, numEdges;
}MGraph;

void CreateMGraph(MGraph *G)
{
int i,j,k,w;
printf(“输入定点数和边数:\n”);
scanf(“%d,%d”, &G->numVertexes, &G->numEdges);
for(i =0; i < G->numVertexes; i++)
{
scanf(&G->vexs[i]);
}
for(i = 0; i < G->numVertexes;i++)
{
for(j = 0; j < G->numVertexes;j++)
{
G->arc[i][j] = INFINITY;
}
}
for(k = 0;k < G->numEdges; k++)
{
printf(“输入边(vi, vj)上的下标i,下标j和权w:\n”);
scanf(“%d,%d,%d”, &i, &j, &w);
G->arc[i][j] =w;
G->arc[j][i] =G->arc[i][j];
}

}
int main()
{
MGraph MG;
CreateMGraph(&MG);
return 1;
}
图的深度优先遍历(java):
public class TestGraph {
private boolean[] visited; //是否遍历过
private int[][] graph; //二维数组图
private final int n = 5; //n个点
public TestGraph()
{
this.initGraph(); //初始化图数据
}
private void initGraph()
{
visited = new boolean[n];
graph = new int[n][n]; //二维数组
int i = 0;
int j = 0;
for(i = 0; i < n; i++)
{
visited[i] = false; //把n个点都设为未遍历过
for(j = 0; j < n; j++)
{
graph[i][j] = 0;
}
}

    //例,把可能过的设为1   
    graph[0][1] = 1;graph[1][0] = 1; //点1-2   
    graph[0][4] = 1;graph[4][0] = 1; //点1-5   
    graph[1][2] = 1;graph[2][1] = 1; //点2-3   
    graph[1][3] = 1;graph[3][1] = 1; //点2-4   
    graph[2][4] = 1;graph[4][2] = 1; //点3-5   

}   


private void showPath(int x)   
{   
    for(int i = 0; i < n; i++)   
    {   
        if(graph[x][i] == 1 && visited[i] == false) //从x点到i点,如果可以通而且未遍历过   
        {   
            visited[i] = true; //设置为到达   
            System.out.print(i); //打印路径   
            showPath(i); //递归遍历点   
        }   
    }   
}   


public static void main(String[] args)   
{   
    int begin = 0; //从哪点开始   
    TestGraph testGraph = new TestGraph();   
    testGraph.showPath(begin);   
}   

}
//图的广度优先遍历(MGraph为邻接矩阵)
void BFSTraverse(MGraph G){
int i,j;
Queue Q;
for(i = 0; i < G.numVertexes; i++)
{
visited[i] = false;
}
initQueue(&Q);/初始化辅助队列/
for(i = 0; i < G.numVertexes; i++)
{
if(!visited[i])
{
visited[i] = true;
printf(“%c”,G.vexs[i]);
EnQueue(&Q,&i);
while(!QueueEmpty(Q))
{
DeQueue(&Q,&i);/将队列中的元素出队列,复制给i/
for(j =0; j < G.numVertexes; j++)
{
if(G.arc[i][j] == 1 && !visited[j])
{
visited[j] = true;
printf(“%c”,G.vexs[j]);
EnQueue(&Q,j);/将找到的此顶点入队列/
}
}
}
}
}
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/xinlingchengbao/article/details/52420385
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞