"""File: dfs.py Purpose: Implement depth-first search of a digraph in Python Run: python dfs.py Input: Number of vertices in digraph Adjacency matrix of digraph Output: Order in which DFS visits the vertices """ #---------------------------------------------------------------------- def get_matrix(n): """Read in and return a matrix of ints with n rows and n columns""" mat = [] print "Enter the rows of the matrix, one row per line" for i in range(n): row_str = raw_input("") row_str_l = row_str.split() row = [] for j in range(n): row.append(int(row_str_l[j])) mat.append(row) return mat #---------------------------------------------------------------------- def print_matrix(mat, n): """Print a matrix with n rows and n columns""" for i in range(n): for j in range(n): print mat[i][j], print #---------------------------------------------------------------------- def all_false(n): """Create a list, all of whose elements are False""" visited = [] for i in range(n): visited.append(False) return visited #---------------------------------------------------------------------- def print_list(l): """Print the contents of a list""" for i in l: print i, print #---------------------------------------------------------------------- def depth_first_search(vert, mat, visited, n): """Visit the vertices in the digraph using depth-first search""" print "Visiting", vert visited[vert] = True for i in range(n): if mat[vert][i] == 1 and not visited[i]: depth_first_search(i, mat, visited, n) #---------------------------------------------------------------------- n = int(raw_input("How many vertices\n ")) mat = get_matrix(n) print print_matrix(mat, n) visited = all_false(n) #print #print_list(visited) print depth_first_search(0, mat, visited, n)