Python code example for constructing a graph using an adjacent matrix, python Matrix
Problem
How to use the list structure diagram
Method of the adjacent matrix
Python sample code
#! /Usr/bin/env python #-*-encoding: UTF-8-*-# author: LiYanwei # version: 0.1 # '''a --- B \ | |\| | c |/e --- d/if an edge exists between an undirected graph vertex, the value is 1, otherwise, 0 a B c d ea 0 1 0 0 1b 1 0 1 1 0c 0 1 0 1 0 1 0d 0 1 1 0 1e 1 0 0 1 0 0 observed that the foot line is symmetric directed graph, if a ---> B exists, the value of AB is 1, and the value of ba is 0. You can set the corresponding numerical defect: 1. for images with few fixed-point multilateral points, the matrix space is wasted. 2. to obtain the adjacent vertex of a vertex, traverse the corresponding list and find the 1 vertex ''' # construct the vertex list to resolve N = 5a, B, c, d, e = xrange (5) G = [[0] * N for _ in xrange (5)] # undirected graph construction edge def addEdge (G, v1, v2 ): G [v1] [v2] = G [v2] [v1] = 1 addEdge (G, a, B) addEdge (G, B, c) addEdge (G, B, d) addEdge (G, B, e) addEdge (G, d, e) addEdge (G, d, c) print G
Result:
[[0, 1, 0, 0, 0], [1, 0, 1, 1, 1], [0, 1, 0, 1, 0], [0, 1, 1, 0, 1], [0, 1, 0, 1, 0]]
Summary
The above is all the content of the code example of using the adjacent matrix to build a graph in python. I hope it will be helpful to you. If you are interested, you can continue to refer to this site: python first traverses Binary Tree problems, Python3 calls the enterprise number API to send text message code samples, python to implement face recognition code, etc. If you have any questions, you can leave a message at any time, the editor will reply to you in a timely manner. Thank you for your support!