python实现dict版图遍历示例

yipeiwu_com6年前Python基础

复制代码 代码如下:

#_*_coding:utf_8_
import sys
import os

class Graph():
    def __init__(self, V, E):
        self.V = V
        self.E = E
        self.visited = []
        self.dict = {}
        self.fd = open("input.txt")

    def initGraph(self):
        self.visited = [0 for i in range(self.V+1)]
        for i in range(self.E):
            f, t = map(int, self.fd.readline().split())
            #f, t = map(int, sys.stdin.readline().split())
            if self.dict.has_key(f)==False:
                l = []
                l.append(t)
                self.dict[f] = l
            else:
                l = self.dict[f]
                l.append(t)
                self.dict[f] = l

   
    def dfsGraph(self, src):
        self.visited[src] = 1
        print src ,
        if self.dict.get(src): #self.dict[src]会出现异常
            for u in self.dict[src]:
                if self.visited[u]==0:
                    self.dfsGraph(u)

graph = Graph(6, 10)
graph.initGraph()
graph.dfsGraph(1)

nput.txt

复制代码 代码如下:

1 2
1 3
1 4
3 2
2 6
4 3
3 5
4 5
6 5
3 6

output:

复制代码 代码如下:

1 2 6 5 3 4

相关文章

python将txt文档每行内容循环插入数据库的方法

如下所示: import pymysql import time import re def get_raw_label(rece): re1 = r'"([\s\S]*?...

使用Python实现图像标记点的坐标输出功能

使用Python实现图像标记点的坐标输出功能

Sometimes we have need to interact  with an application,for example by marking points in...

从django的中间件直接返回请求的方法

实例如下所示: #coding=utf-8 import json import gevent from django.http import HttpResponse from s...

Python学习笔记之变量、自定义函数用法示例

本文实例讲述了Python变量、自定义函数用法。分享给大家供大家参考,具体如下: 不管你学什么编程语言 都逃不出如下套路: 1、怎么定义变量?是否有数据类型,怎么在控制台输出? 2、怎...

python实现将json多行数据传入到mysql中使用

将json多行数据传入到mysql中使用python实现 表需要提前创建,字符集utf8 如果不行换成utf8mb4 import json import pymysql def...