def test():
    datasetfile = ['Email-Enron']#['com-dblp.ungraph', 'Email-Enron', 'facebook_combined']
    order = ['bfs', 'dfs', 'rand']
    ksize = [4,8,12]
    ba,ch,dg,ha,rg,tr=[],[],[],[],[],[]
    Edges_constant = [1049866,367662,88234]  #edges of each datasets
    for dataname in datasetfile:
        txt2p.txt2p(dataname)
        rand.Rand(dataname)
        dfs.dfs(dataname)
        bfs.bfs(dataname)
    for dataname in datasetfile:
        for od in order:
            for k in ksize:
                ba.append(Balanced.Balanced(dataname, k, od))
                ch.append(Chunking.Chunking(dataname, k, od))
                dg.append(DGreedy.DGreedy(dataname, k, od))
                ha.append(Hashing.Hashing(dataname, k, od))
                rg.append(RGreedy.RGreedy(dataname, k, od))
                tr.append(Triangles.Triangles(dataname, k, od))
                
    print 'ba',ba
    print 'ch',ch
    print 'dg',dg
    print 'ha',ha
    print 'rg',rg
    print 'tr',tr
Exemplo n.º 2
0
def topo_sort(graph):
    """
    Given a directed graph, return an ordering of nodes ordered by when they can be processed.
    None if cycles exist or if graph is undirected.

    After a node is processed, push it onto a stack, and if at any time we have a BACK edge
    then terminate the process.  Note that the graph can be unconnected so run a DFS from
    all undiscovered nodes.
    """
    class TSTraversal(dfs.Traversal):
        def __init__(self, graph):
            dfs.Traversal.__init__(self, graph)
            self.stack = []

        def node_processed(self, node):
            self.stack.append(node)

        def process_edge(self, source, target, edge):
            """
            When processing an edge ensure we have no back edges.
            """
            if target in self.node_state and self.node_state[
                    target] == dfs.DISCOVERED:
                self.terminated = True

    traversal = TSTraversal(graph)
    for node in graph.nodes:
        if node not in traversal.node_state:
            dfs.dfs(node, traversal)
            if traversal.terminated:
                return False, None

    return True, traversal.stack
Exemplo n.º 3
0
def topsort_dfs(graph):
    sorted_stack = []
    visited = []
    visit = topsort_visit(sorted_stack) 
    for k, v in graph.vertices.items():
        if v not in visited:
            dfs.dfs(v, visited, visit)
    sorted_stack.reverse()
    return sorted_stack 
def main():
    roads = snap.LoadEdgeList(snap.PNGraph, "roadNet-TX.txt")
    #roads = snap.LoadEdgeList(snap.PNGraph, "cgl_sample.txt")
    roadnet = snap.ConvertGraph(snap.PNEANet, roads)
    print roadnet
    dfs.dfs(roadnet)
    print dfs.g_visit_num
    
    return
Exemplo n.º 5
0
def topsort_dfs(graph):
    sorted_stack = []
    visited = []
    visit = topsort_visit(sorted_stack)
    for k, v in graph.vertices.items():
        if v not in visited:
            dfs.dfs(v, visited, visit)
    sorted_stack.reverse()
    return sorted_stack
Exemplo n.º 6
0
def find_path(digraph, from_node, to_node):
    assert from_node in digraph.nodes()
    assert to_node in digraph.nodes()

    visitor = FindPathVisitor(node=to_node)
    dfs.dfs(digraph=digraph, node=from_node, visitor=visitor)
    if visitor.found():
        return visitor.path()
    return []
def acyclic(adj, version=2):
    try:
        if version == 2:
            dfs.dfs2(adj)
        else:
            dfs.dfs(adj)
    except dfs.HasCycleException as e:
        # print(e)
        return 1
    return 0
Exemplo n.º 8
0
    def test_dfs_int_vertices_negaitve(self):

        graph = Graph()

        graph.add_edge(Edge(Vertex(1), Vertex(2), 1))
        graph.add_edge(Edge(Vertex(1), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(3), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(4), Vertex(2), 1))

        self.assertEqual(dfs(graph, Vertex(5), Vertex(0)), float("inf"))
        self.assertEqual(dfs(graph, Vertex(1), Vertex(5)), float("inf"))
Exemplo n.º 9
0
def toposort_node(digraph, node):
    v = TopoVisitor()
    try:
        dfs.dfs(digraph=digraph, node=node, visitor=v)
    except cycle.CycleError, error:
        # annotate cycle
        edgelist = []
        for tail, head in [(error.nodelist()[i], error.nodelist()[i + 1])
                           for i in xrange(len(error.nodelist()) - 1)]:
            edge = digraph.find_edge(tail, head)
            assert edge is not None
            edgelist.append(edge)
            pass
        raise cycle.CycleError(nodelist=error.nodelist(), edgelist=edgelist)
Exemplo n.º 10
0
def test(title, problem):
    print('\nTesting %s problem...' % title)
    board = Board(text_to_data(problem))
    sudoku = Sudoku(board)
    boards = dfs(sudoku)
    print('%d Board objects instantiated' % Board.num_objects)
    assert boards[-1].verify()
Exemplo n.º 11
0
def mk_rooted_tree(G, root):
    """
    This function reproduces G as a directed tree pointing away from the
    root.
    Parameters
    ----------
    G: Numpy ndarray
        G[i,j] = 1 iff there is an edge between node i and node j.
    root: Int
        The index of the root node.
    Output
    ------
    T: Numpy ndarray
        The rooted tree, T[i,j] = 1 iff there is an edge between node i and
        node j.
    pre: List
        The pre visting order.
    post: List
        The post visting order.
    cycle: Int
        Equals 1 if there is a cycle in the rooted tree.
    """
    n = G.shape[0]
    T = np.zeros((n, n))
    directed = 0
    """Preform depth first search"""
    searched = dfs(G, root, directed)

    for i in range(0, searched.pred.shape[1]):
        if searched.pred[0, i] != -1:
            T[searched.pred[0, i], i] = 1

    return [T, searched.pre, searched.post, searched.cycle]
Exemplo n.º 12
0
def start():
    print("enter choice 1.bfs 2.dfs 3.uniform cost search 4.astart")
    x=input()
    if x=="1":
        graph={}
        print("enter number  nodes")
        nodes=int(input())
        for i in range(0,nodes):
            print("enter nodes connected to node with spaces:"+str(i))
            x=list(input().split())
            x = [int(i) for i in x]
            graph[i]=x
        goal=int(input("enter goal state"))
        print('bfs ' +bfs.bfs(graph,0,goal))
    if x=="2":
        graph=[]
        print("enter number  nodes")
        nodes = int(input())
        for i in range(0, nodes):
            print("enter nodes connected to node with spaces:" + str(i))
            x = list(input().split())
            x = [int(i) for i in x]
            graph.append(x)
        goal = int(input("enter goal state"))
        print(dfs.dfs(graph, 0,goal))
    if x=="3":
        djikstra.start1()

    if x=="4":
        astardynamic.start()
Exemplo n.º 13
0
def SearchUSA(search_type, src_city, dst_city, filename='roads.txt'):
    "This function searches for a path from source city to destination city using given search algorithm"

    import bfs, dfs, astar, Roadmap
    from HelperFunctions import ReadFileToMap

    #Initializing empty map which uses adjacency list data structure to store map information
    my_map = Roadmap.Roadmap()

    #Loading map from the text file
    ReadFileToMap(filename, my_map)

    success = False

    print("\nApplying '{0}' Algorithm to search path from {1} to {2}\n".format(
        search_type.upper(), src_city.upper(), dst_city.upper()))

    if (search_type == 'bfs'):
        #		print("\n{}".format("BFS SEARCH".center(80,'$')))
        success = bfs.bfs(src_city, dst_city, my_map)
    elif (search_type == 'dfs'):
        #		print("\n{}".format("DFS SEARCH".center(80,'$')))
        success = dfs.dfs(src_city, dst_city, my_map)
    elif (search_type == 'astar'):
        #		print("\n{}".format("ASTAR SEARCH".center(80,'$')))
        success = astar.astar(src_city, dst_city, my_map)
    else:
        print("\nInvalid Search Type: Please Try Again.\n")

    if (success):
        pass
        # print("{}\n".format("SUCESS".center(400,'*')))
    else:
        print("{}\n".format("FAILURE".center(400, '*')))
Exemplo n.º 14
0
 def cycle_check(self):
     """Check the DAG for illegal cycles in the include structure.
     @rtype: bool
     @return: True if the DAG contains cycles (and thus is not a DAG).
     """
     node_dict = {}
     # build the graph for the DFS
     for k, v in self.recs.iteritems():
         if k in node_dict:
             node = node_dict[k]
         else:
             node = dfs.node_t(k)
             node_dict[k] = node
         for p in v.files_that_are_inputs:
             if p in node_dict:
                 pnode = node_dict[p]
             else:
                 pnode = dfs.node_t(p)
                 node_dict[p] = pnode
             node.add_successor(pnode)
     # Traverse the graph
     cycle = dfs.dfs(node_dict.values())
     if cycle:
         msgb("CYCLE DETECTED IN DAG")
     return cycle
Exemplo n.º 15
0
def main():
    print("\n\n\nEnter the maze number that you want to solve.")
    mazeNumber = int(input("[1]. maze1.txt \t 2. maze2.txt \t 3. maze3.txt\n"))

    print("\n\nEnter algorithm number you would like to use.")
    algoPref = int(
        input(
            "[1]. Djikstra's \n 2. Breadth First Searh \n 3. Depth First Search \n 4. Backtracking\n"
        ))

    print("\n\nDo you want to get the output in color?")
    color = input("[Y]es\t\tNo\n")

    maze, start, end = mazes(mazeNumber)

    if algoPref == 4:
        path = backtracking(maze, start)
    elif algoPref == 3:
        path = dfs(maze, start)
    elif algoPref == 2:
        path = bfs(maze, start)
    else:
        path = djikstras(maze, start)

    # Printing the maze with the solution for the respective path finding algorithm
    currNode = end
    while currNode != (0, 1):
        nextNode = path[currNode]
        connectTwoCells(maze, currNode, nextNode)
        currNode = nextNode
    if color == "Y" or color == "y" or color.capitalize() == "Yes":
        printMazeInColor(maze)
    else:
        printMaze(maze)
Exemplo n.º 16
0
def get_dfs():
    if (dfs(maze, 0, 0, path, visited, draw_maze) == False):
        canvas.create_text(100,
                           100,
                           font=("Times New Roman", 20, "bold"),
                           fill='pink',
                           text="no solution")
Exemplo n.º 17
0
 def test_dfs(self):
     g = Graph('a',[op2])
     path = dfs(g,goal_predicate1)
     self.assertFalse(path is None)            
     self.assertTrue(['a', 'b' ,'c', 'd'] == map(lambda x: x.data, path) or \
                     ['a', 'b', 'd'] == map(lambda x: x.data, path) or \
                     ['a', 'c', 'd'] == map(lambda x: x.data, path))
def choose_algo(start, end, grid, algorithm):
    if algorithm == 'bfs':
        return bfs(start, end, grid)
    elif algorithm == 'dfs':
        return dfs(start, end, grid)
    elif algorithm == 'dijkstra':
        return dijkstra(start, end, grid)
    elif algorithm == 'astar':
        return astar(start, end, grid)
Exemplo n.º 19
0
def move(start, target, grid, algorithm):
    if algorithm == "astar":
        return astar(start, target, grid)
    elif algorithm == "dijkstra":
        return dijkstra(start, target, grid)
    elif algorithm == "bfs":
        return bfs(start, target, grid)
    elif algorithm == "dfs":
        return dfs(start, target, grid)
Exemplo n.º 20
0
    def test_dfs_str_vertices_negative(self):

        graph = Graph()

        graph.add_edge(Edge(Vertex("A"), Vertex("D"), 2))
        graph.add_edge(Edge(Vertex("A"), Vertex("G"), 3))
        graph.add_edge(Edge(Vertex("A"), Vertex("B"), 1))
        graph.add_edge(Edge(Vertex("B"), Vertex("E"), 6))
        graph.add_edge(Edge(Vertex("B"), Vertex("F"), 7))
        graph.add_edge(Edge(Vertex("F"), Vertex("D"), 10))
        graph.add_edge(Edge(Vertex("F"), Vertex("C"), 12))
        graph.add_edge(Edge(Vertex("E"), Vertex("G"), 9))

        self.assertEqual(dfs(graph, Vertex("A"), Vertex("C")), 20)
        self.assertEqual(dfs(graph, Vertex("A"), Vertex("F")), 8)
        self.assertEqual(dfs(graph, Vertex("B"), Vertex("G")), 15)
        self.assertEqual(dfs(graph, Vertex("E"), Vertex("A")), float("inf"))
        self.assertEqual(dfs(graph, Vertex("C"), Vertex("D")), float("inf"))
Exemplo n.º 21
0
	def testBfs(self):
		G = graph.Graph()
		G.addEdge(1,2)
		G.addEdge(2,3)
		G.addEdge(4,1)
		G.addEdge(5,1)
		G.addEdge(6,1)
		G.addEdge(7,6)
		G.addEdge(3,1)
		G.addEdge(8,7)
		G.addEdge(9,8)
		G.addEdge(2,8)
		G.addEdge(9,10)
		processingOrder = []
		def processFun(v, visited):
			if v not in visited:
				processingOrder.append(v)
		dfs.dfs(G, 1, processFun, lambda v : v)
		self.failUnlessEqual(processingOrder, [1,2,8,9,10,7,6,3,4,5])
Exemplo n.º 22
0
def searchSelect(ch):
    if (ch == 1):
        dfs(graph, START, GOAL)
        return
    if (ch == 2):
        bfs(graph, START, GOAL)
        return
    if (ch == 3):
        depth = int(raw_input("Enter Depth :"))
        dls(graph, START, GOAL, depth)
        return
    if (ch == 4):
        ufs(weightGraph, START, GOAL)
        return
    if (ch == 5):
        greedySearch(graph, list_of_heuristic, START, GOAL)
        return
    if (ch == 6):
        aStarSearch(weightGraph, list_of_heuristic, START, GOAL)
        return
def drawer():
    win = pygcurse.PygcurseWindow(config['board']['w'],
                                  config['board']['h'],
                                  fgcolor='black')
    win.setscreencolors(None, 'white', clear=True)
    drag = False
    startEnd = []
    while len(startEnd) < 2:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN
                                      and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONUP:
                coordinate = win.getcoordinatesatpixel(event.pos)
                win.write('@', *coordinate)
                startEnd.append(coordinate)

    walls = set()
    while True:
        for event in pygame.event.get():
            if event.type == QUIT or (event.type == KEYDOWN
                                      and event.key == K_ESCAPE):
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN:
                drag = True
            elif event.type == pygame.MOUSEBUTTONUP:
                drag = False
            elif event.type == pygame.MOUSEMOTION:
                if drag:
                    coordinate = win.getcoordinatesatpixel(event.pos)
                    win.write('#', *coordinate)
                    walls.add(coordinate)
            elif event.type == pygame.KEYDOWN:
                if config['algo'] == 'bfs':
                    bfs(win, startEnd, walls)
                if config['algo'] == 'dfs':
                    dfs(win, startEnd, walls)
                if config['algo'] == 'astar':
                    a_star(win, startEnd, walls)
Exemplo n.º 24
0
    def test_dfs_int_vertices_positive(self):

        graph = Graph()

        graph.add_edge(Edge(Vertex(0), Vertex(1), 1))
        graph.add_edge(Edge(Vertex(0), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(1), Vertex(0), 1))
        graph.add_edge(Edge(Vertex(1), Vertex(3), 1))
        graph.add_edge(Edge(Vertex(1), Vertex(4), 1))
        graph.add_edge(Edge(Vertex(1), Vertex(2), 1))
        graph.add_edge(Edge(Vertex(2), Vertex(3), 1))
        graph.add_edge(Edge(Vertex(2), Vertex(1), 1))
        graph.add_edge(Edge(Vertex(3), Vertex(1), 1))
        graph.add_edge(Edge(Vertex(3), Vertex(2), 1))
        graph.add_edge(Edge(Vertex(3), Vertex(4), 1))

        self.assertEqual(dfs(graph, Vertex(2), Vertex(0)), 3)
        self.assertEqual(dfs(graph, Vertex(2), Vertex(1)), 2)
        self.assertEqual(dfs(graph, Vertex(2), Vertex(2)), 0)
        self.assertEqual(dfs(graph, Vertex(2), Vertex(3)), 1)
        self.assertEqual(dfs(graph, Vertex(2), Vertex(4)), 4)
Exemplo n.º 25
0
def dfs_connected(graph):
    connected_components = list()
    discovered_nodes = set()
    for node in graph.keys():
        if node not in discovered_nodes:
            connected = dfs.dfs(graph, node)
            connected_components.append(connected)
            discovered_nodes = discovered_nodes.union(connected)
            print 'connected_components', connected_components
            print 'discovered_nodes', discovered_nodes

    return connected_components
Exemplo n.º 26
0
    def recognizes(self, text):
        pc = set()
        pre, _, _ = dfs(self.G, [self.G[0]])
        for v in pre:
            pc.add(v)

        for c in text:
            match = set()
            for v in pc:
                if v.name < self.M:
                    if self.re[v.name] == c or self.re[v.name] == ".":  # matched
                        match.add(self.G[v.name + 1])
            pc.clear()
            pre, _, _ = dfs(self.G, match)
            for v in pre:
                pc.add(v)

        for v in pc:
            if v.name == self.M:
                return True
        return False
Exemplo n.º 27
0
    def test_connected_graph(self):
        graph = {'A': ['B', 'C'],
                 'B': ['F', 'D'],
                 'C': ['D', 'E'],
                 'D': [],
                 'E': [],
                 'F': []
                }
        start = 'A'
        out_visited = ['A', 'B', 'F', 'D', 'C', 'E']

        self.assertEqual(dfs(graph, start), out_visited)
Exemplo n.º 28
0
def test():
    graph1 = {
        1: [2, 3],
        2: [4, 5],
        3: [6],
    }

    assert bfs(graph1, start_node=1) == [1, 2, 3, 4, 5, 6]
    assert dfs(graph1, 1) == [1, 2, 4, 5, 3, 6]
    assert toposort(graph1) == [1, 3, 6, 2, 5, 4]

    graph2 = {
        6: [4, 5],
        5: [2, 0],
        4: [0, 1],
        2: [3],
        3: [1],
    }

    assert bfs(graph2, 6) == [6, 4, 5, 0, 1, 2, 3]
    assert dfs(graph2, 6) == [6, 4, 0, 1, 5, 2, 3]
    assert toposort(graph2) == [6, 5, 2, 3, 4, 1, 0]
Exemplo n.º 29
0
def main():
    g1 = nx.DiGraph()
    print(g1)
    g1.add_nodes_from([1,2,3,4,5])
    g1.add_edges_from([(1,2), (1,5), (2,3), (5,4)])

    g1.nodes[1]['value'] = 'a'
    g1.nodes[2]['value'] = 'operation'
    g1.nodes[3]['value'] = 'doido'
    g1.nodes[4]['value'] = 'animal'
    g1.nodes[5]['value'] = 'a10'
    result = dfs(g1, 'animal')
    print(result)
Exemplo n.º 30
0
 def test_easy_2(self):
     board = Board([[2, 7, 4, 0, 0, 0, 5, 8,
                     0], [0, 0, 0, 0, 0, 8, 2, 0, 0],
                    [6, 0, 3, 5, 4, 2, 0, 0,
                     0], [3, 0, 1, 2, 0, 0, 8, 0, 0],
                    [0, 0, 0, 8, 6, 4, 0, 0,
                     0], [0, 0, 8, 0, 0, 3, 6, 0, 5],
                    [0, 0, 0, 3, 2, 7, 9, 0,
                     8], [0, 0, 2, 1, 0, 0, 0, 0, 0],
                    [0, 1, 9, 0, 0, 0, 3, 2, 7]])
     sudoku = Sudoku(board)
     boards = dfs(sudoku)
     self.assertTrue(boards[-1].filled())
     self.assertTrue(boards[-1].verify())
Exemplo n.º 31
0
 def test_evil(self):
     board = Board([[0, 1, 8, 0, 6, 0, 0, 0,
                     0], [3, 0, 0, 0, 0, 9, 0, 0, 0],
                    [0, 0, 9, 0, 0, 3, 4, 0,
                     0], [0, 9, 0, 1, 0, 0, 0, 0, 5],
                    [0, 4, 2, 0, 0, 0, 7, 1,
                     0], [5, 0, 0, 0, 0, 2, 0, 8, 0],
                    [0, 0, 4, 5, 0, 0, 6, 0,
                     0], [0, 0, 0, 8, 0, 0, 0, 0, 7],
                    [0, 0, 0, 0, 7, 0, 8, 4, 0]])
     sudoku = Sudoku(board)
     boards = dfs(sudoku)
     self.assertTrue(boards[-1].filled())
     self.assertTrue(boards[-1].verify())
Exemplo n.º 32
0
 def test_extra(self):
     board = Board([[1, 4, 0, 0, 0, 0, 9, 0,
                     0], [0, 0, 3, 8, 6, 1, 0, 0, 0],
                    [5, 0, 0, 0, 0, 0, 0, 0,
                     0], [2, 0, 9, 0, 0, 0, 0, 7, 0],
                    [0, 0, 0, 5, 2, 0, 0, 0,
                     0], [0, 0, 1, 6, 0, 0, 3, 5, 0],
                    [0, 8, 0, 0, 0, 0, 7, 0,
                     6], [0, 0, 0, 3, 0, 0, 0, 0, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0, 0]])
     sudoku = Sudoku(board)
     boards = dfs(sudoku)
     self.assertTrue(boards[-1].filled())
     self.assertTrue(boards[-1].verify())
Exemplo n.º 33
0
 def test_easy_3(self):
     board = Board([[0, 0, 0, 0, 9, 2, 0, 0,
                     0], [0, 7, 9, 6, 0, 5, 0, 8, 0],
                    [3, 0, 0, 1, 0, 0, 0, 0,
                     5], [0, 3, 0, 0, 0, 6, 0, 4, 2],
                    [0, 2, 6, 5, 8, 4, 3, 1,
                     0], [5, 4, 0, 2, 0, 0, 0, 6, 0],
                    [1, 0, 0, 0, 0, 3, 0, 0,
                     6], [0, 5, 0, 7, 0, 1, 8, 3, 0],
                    [0, 0, 0, 4, 2, 0, 0, 0, 0]])
     sudoku = Sudoku(board)
     boards = dfs(sudoku)
     self.assertTrue(boards[-1].filled())
     self.assertTrue(boards[-1].verify())
Exemplo n.º 34
0
 def test_medium(self):
     board = Board([[0, 0, 0, 0, 8, 0, 0, 0,
                     0], [4, 5, 8, 0, 0, 0, 0, 2, 0],
                    [6, 9, 2, 0, 4, 0, 0, 0,
                     1], [0, 0, 0, 7, 0, 0, 3, 8, 2],
                    [0, 1, 0, 0, 0, 0, 0, 6,
                     0], [2, 7, 5, 0, 0, 3, 0, 0, 0],
                    [7, 0, 0, 0, 2, 0, 9, 1,
                     3], [0, 2, 0, 0, 0, 0, 6, 5, 8],
                    [0, 0, 0, 0, 1, 0, 0, 0, 0]])
     sudoku = Sudoku(board)
     boards = dfs(sudoku)
     self.assertTrue(boards[-1].filled())
     self.assertTrue(boards[-1].verify())
Exemplo n.º 35
0
 def test_hard(self):
     board = Board([[7, 0, 6, 5, 0, 9, 0, 4,
                     0], [0, 0, 0, 3, 7, 0, 0, 9, 0],
                    [9, 0, 0, 0, 0, 0, 0, 0,
                     0], [0, 9, 0, 0, 0, 0, 0, 0, 4],
                    [1, 0, 7, 0, 4, 0, 5, 0,
                     3], [2, 0, 0, 0, 0, 0, 0, 7, 0],
                    [0, 0, 0, 0, 0, 0, 0, 0,
                     6], [0, 1, 0, 0, 3, 4, 0, 0, 0],
                    [0, 6, 0, 8, 0, 7, 1, 0, 9]])
     sudoku = Sudoku(board)
     boards = dfs(sudoku)
     self.assertTrue(boards[-1].filled())
     self.assertTrue(boards[-1].verify())
Exemplo n.º 36
0
    def use_dfs(start_coord, wall_li, grid_x, grid_y, end):
        # Find Path
        visited, has_path = dfs(start_coord, wall_li, (grid_x, grid_y), end)

        for cell in range(1, len(visited)):
            x, y = visited[cell]
            grid[x][y].color = yellow
            grid[x][y].is_path = True
            redraw_window()
        if has_path:
            x, y = Rectangle.end_coord
            grid[x][y].color = dark_red
        else:
            print("No solution")
Exemplo n.º 37
0
 def test_easy_1(self):
     board = Board([[6, 0, 0, 9, 2, 0, 0, 3,
                     8], [3, 0, 0, 6, 7, 0, 0, 1, 5],
                    [0, 1, 9, 0, 3, 0, 0, 0,
                     0], [0, 0, 0, 3, 6, 0, 0, 5, 0],
                    [2, 6, 0, 0, 0, 0, 0, 7,
                     3], [0, 4, 0, 0, 5, 7, 0, 0, 0],
                    [0, 0, 0, 0, 8, 0, 5, 2,
                     0], [4, 8, 0, 0, 9, 3, 0, 0, 7],
                    [5, 7, 0, 0, 1, 2, 0, 0, 9]])
     sudoku = Sudoku(board)
     boards = dfs(sudoku)
     self.assertTrue(boards[-1].filled())
     self.assertTrue(boards[-1].verify())
Exemplo n.º 38
0
def mk_rooted_tree(G, root):
    """
    This function reproduces G as a directed tree pointing away from the
    root.

    Parameters
    ----------
    G: Numpy ndarray
        G[i,j] = 1 iff there is an edge between node i and node j.

    root: Int
        The index of the root node.

    Output
    ------
    T: Numpy ndarray
        The rooted tree, T[i,j] = 1 iff there is an edge between node i and
        node j.

    pre: List
        The pre visting order.

    post: List
        The post visting order.

    cycle: Int
        Equals 1 if there is a cycle in the rooted tree.
    """
    n = G.shape[0]
    T = np.zeros((n, n))
    directed = 0

    """Preform depth first search"""
    searched = dfs(G, root, directed)

    for i in range(0, searched.pred.shape[1]):
        if searched.pred[0, i]!=-1:
            T[searched.pred[0, i], i] = 1

    return [T, searched.pre, searched.post, searched.cycle]
Exemplo n.º 39
0
def test_non_first_child():
    root = Tree(6)
    root.add_child(Tree(2))
    root.add_child(Tree(1))
    assert dfs(root, 1)
Exemplo n.º 40
0
def test_single_child():
    root = Tree(6)
    root.add_child(Tree(2))
    assert dfs(root, 2)
Exemplo n.º 41
0
def test_not_in_tree():
    root = Tree(6)
    root.add_child(Tree(2))
    assert not dfs(root, 1)
Exemplo n.º 42
0
def test_empty():
    assert not dfs(None, 3)
Exemplo n.º 43
0
def test_single_item():
    root = Tree(6)
    assert dfs(root, 6)
Exemplo n.º 44
0
	def test_dfs(self):
		size = 4
		MAT = np.zeros((size, size))
		dfs(MAT, 0, 0, size, size)
Exemplo n.º 45
0
"""
Input is of the form (n and then edges) :
n
u1 v1
u2 v2
u3 v3
.
.
.
un vn
"""

# no of edges
n = int(input())

# for directed graph
adj = {}
for i in range(n):
	key, val = map(int, input().split(' '))
	if key not in adj:
		adj[key] = [val]
	else:
		adj[key].append(val)

	if val not in adj:
		adj[val] = []

print(adj)
dfs(adj)
Exemplo n.º 46
0
			3			11
		/		\	/		\
		1		5	9		13
	0		2  4       6 	810	12		14
		

"""
class Node:
	def __init__(self,cargo,left, right):
		self.cargo = cargo
		self.left = left
		self.right = right

def create_binary_tree(array):
	length = len(array)
	half = length/2
	if half > 0:
		left = create_binary_tree(array[0:half])
	else: 
		left = None
	if len(array) - (half+1) > 0:
		right = create_binary_tree(array[half+1:])
	else: 
		right = None
	root = Node(str(array[half]),left,right)
	return root
global toWrite
root = create_binary_tree(X)
X = dfs.dfs(root)
print X
Exemplo n.º 47
0
# *****




time_beg = time.time()
def my_print(s):
    dfs.report_file.write(s + "\n")
    print(s)

def im(num, path):
    time_image = time.time()
    try:
        image = Image.open(path)
        image.save(path, "JPEG", quality = 75)
        my_print("#%d : Ok : %s" % (num, path))
        my_print("\ttime = %.6f" % (time.time() - time_image))
        my_print("\tTotal time = %.6f" % (time.time() - time_beg))
    except:
        my_print("\nError in file: %s" % path)
        my_print("\ttime = %.6f" % (time.time() - time_image))
        my_print("\tTotal time = %.6f" % (time.time() - time_beg))

#image.thumbnail((image.size[0] // 2, image.size[1] // 2), Image.ANTIALIAS)

dfs.dfs("")
for i, item in enumerate(dfs.images_files):
    im(i, item)

my_print("*\n**Total time = %.6f***" % (time.time() - time_beg))