Python code example for constructing a graph using an adjacent matrix, python Matrix

Source: Internet
Author: User

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!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.