예제 #1
0
def algorithm(matrix):
    print("__________________________")
    print("Which Algorithm you want to use ?\n")
    print("For A* Print A")
    print("For Best First Search Print G")
    print("For BFS print B")
    choose = input().upper()

    if choose == "A":
        os.system("clear")
        print("You have choosen A* Algorithm")
        start = Nodes(matrix, None, 0, 0, 'A', None)
        a_start(start, Goal)

    if choose == "G":
        os.system("clear")
        print("You have choosen Mighty! Best First Algorithm")
        start = Nodes(matrix, None, 0, 0, 'G', None)
        bestFirstSearch(start, Goal)

    if choose == "B":
        os.system("clear")
        print("You have choosen bfs algorithm")
        start = Nodes(matrix, None, 0, 0, 'B', None)
        bfs(start, Goal)
    print("Wait Please I'm trying ...")
def findWordLadder(startWord, endWord, wordGraph):
    # 1. do graph traversal starting from node for startWord
    startNode = wordGraph.getNode(startWord)
    endNode = wordGraph.getNode(endWord)
    bfs(wordGraph, startNode)
    # 2. extract word ladder from the graph
    return extractWordLadder(startNode, endNode)
예제 #3
0
def main():
    state = State([[1, 2, 3], [0, 0, 0], [0, 0, 0]])
    # state2 = State([[1,0,0],[0,2,3],[0,0,0]])
    # state3 = State([[0,2,0],[0,0,3],[1,0,0]])
    # state4 = State([[0,0,0],[1,2,3],[0,0,0]])
    # state5 = State([[1,0,0],[0,2,0],[0,0,3]])
    # state6 = State([[0,0,3],[1,2,0],[0,0,0]])
    end_state = State([[0, 0, 0], [0, 0, 0], [1, 2, 3]])

    trace = set()
    trace2 = set()
    trace3 = set()

    bfs(state, end_state, trace)
 def start_rech(self, label, label_1):
     if (self.search_type == "dfs"):
         dfs(self.values[0], self.values[1], label_1)
         self.rech_sequance = trace
         for j in trace:
             i = 0
             for x in self.labels:
                 if (j[i//3][i % 3] == "0"):
                     x["fg"] = "white"
                 else:
                     x["fg"] = "black"
                 x["text"] = j[i//3][i % 3]
                 i = i+1
             if (estEtatFinal(j,  self.values[1])):
                 label["text"] = "Success"
                 label["fg"] = "white"
             else:
                 label["text"] = "Failure"
                 label["fg"] = "red"
         #x = dfs(self.labels, self.values)
         #self.rech_sequance = x.recherche(self.values[0], self.values[1])
     elif (self.search_type == "bfs"):
         x = bfs(self.labels, self.values)
         self.rech_sequance = x.recherche(
             self.values[0], self.values[1], label, label_1)
     else:
         x = a_star(self.labels, self.values)
         self.rech_sequance = x.recherche(
             self.values[0], self.values[1], label, label_1)
def main():
    global start_vertex, goal_vertex, mouse_press, mouse_move

    set_stroke_width(2)

    #  drawing the background
    draw_image(img, 0, 0)

    #  drawing all the vertices and adjacent edges
    for key in vertices_dictionary:
        vertices_dictionary[key].draw_vertex(0, 0, 1)
        vertices_dictionary[key].draw_adjacency_edges(0, 0, 1)

    #  check if start vertex and goal vertex do not hold 'None'
    if start_vertex and goal_vertex:

        #  find a path between them
        bfs_list = bfs(start_vertex, goal_vertex)

        #  draw the edges
        i = 1
        while i <= len(bfs_list) - 1:
            j = i - 1
            bfs_list[i].draw_edge(bfs_list[j], 1, 0, 0)
            i += 1
def main(args):

    # If both args.d and args.n are false, use BFS
    # If args.n is true, use naive
    # If args.d is true, use Dijkstra
    # If args.b is true, use BFS

    graph = pickle.load(open(args.data, 'rb'))

    de_graph = add_dead_ends_to_graph(graph)

    unit_weighted_graph = make_unit_weighted_graph(graph)

    for source_k, source_v in graph.iteritems():
        print source_k.encode('ascii', 'ignore')
        for dest_k, dest_v in graph.iteritems():
            if args.d:
                # use Dijkstra's algorithm
                sp = shortestPath(unit_weighted_graph,source_k,dest_k)
            elif args.n:
                # use naive algorithm
                sp = find_shortest_path(graph,source_k,dest_k,[])
            else:
                # use BFS algorithm
                sp = bfs(graph,source_k,dest_k)
            if sp and len(sp) > 1:
                print len(sp)-1, sp, ":", source_k.encode('ascii', 'ignore'), "->", dest_k.encode('ascii', 'ignore')
예제 #7
0
	def compute(self, list):
		route = []
		results = []
		self.textbox.delete(0, tk.END)
		route.extend(bfs(list[0], list[1]))
		for i in range(1, len(list) - 1):
			results = bfs(list[i], list[i + 1])
			route.extend(results[1:])
		j = 0
		self.clearButtons()
		label = dict((i, '') for i in route)

		for i in route:
			label[i] += str(j) + '   '
			self.buttons[i[0]][i[1]].config(text = str(label[i]))
			j += 1
		self.insertTextBox(str(route))
예제 #8
0
	def startMoves(self):
		while len(self.points) > 1:
			steps = bfs(self.points[0], self.points[1])
			start = steps[0]
			for cur in steps[1:]:
				delta = (cur[0]-start[0],cur[1]-start[1])
				knightMoves(delta[0], delta[1])
				start = cur
			del self.points[0]
예제 #9
0
 def stressTestBfsLevel(self,count):
     print "Started BFS with " + str(count)
     start = time.clock()
     node = self.rotations[count]
     g = Graph(node.data,hungrarianCubeOperators())
     path = bfs(g,hungarianCubePredicate)
     self.assertFalse(path is None)
     elapsed = (time.clock() - start)
     print "Done BFS with " + str(count)+ " levels " +"on " + str(elapsed) +" seconds"
예제 #10
0
    def compute_details(
            self):  #this function is of little importance to the user.

        #This function finds all non trivial details. This may include shortest distance to all powers and the first moves to be made to reach them in shortest time
        #This can also compute other details like the area of the current region in which the bike resides etc..

        self.player1 = bfs()
        self.player2 = bfs()
        self.player1.compute(self.map, self.my_posn)
        self.player2.compute(self.map, self.enemy_posn)

        self.n = len(self.player1.traverser_posn)

        for i in range(self.n):

            self.my_traverser_posn.append(self.player1.traverser_posn[i])
            self.my_traverser_move.append(self.player1.traverser_move[i])
            self.my_traverser_distance.append(
                self.player1.traverser_distance[i])

        self.m = len(self.player1.nitro_posn)

        for i in range(self.m):

            self.my_nitro_posn.append(self.player1.nitro_posn[i])
            self.my_nitro_move.append(self.player1.nitro_move[i])
            self.my_nitro_distance.append(self.player1.nitro_distance[i])

        self.p = len(self.player2.traverser_posn)

        for i in range(self.p):

            self.enemy_traverser_posn.append(self.player2.traverser_posn[i])
            self.enemy_traverser_move.append(self.player2.traverser_move[i])
            self.enemy_traverser_distance.append(
                self.player2.traverser_distance[i])

        self.q = len(self.player2.nitro_posn)

        for i in range(self.q):

            self.enemy_nitro_posn.append(self.player2.nitro_posn[i])
            self.enemy_nitro_move.append(self.player2.nitro_move[i])
            self.enemy_nitro_distance.append(self.player2.nitro_distance[i])
예제 #11
0
 def findBFS(self, start_name):
     g = load_graph()
     
     start = g[start_name]
     # Jasper: maybe change below line to make random? 
     pref = self.preferences[0][0]
     
     end = g[str(pref)]
     path = bfs(start, end)
     return path
예제 #12
0
 def test_oneStepHCube(self):
     cube = HungarianCube()
     node = Node(cube,None,[])
     cube2 = rotateFrontLeft(node)[0].data
     g = Graph(cube2,hungrarianCubeOperators())
     path = bfs(g,hungarianCubePredicate)
     self.assertEquals(len(path),2)
     print path[0].data
     print "-----"
     print path[1].data
예제 #13
0
 def test_stressTestBfs(self):
     print "Stress Test BFS"
     node = self.rotations[4]
     g = Graph(node.data,hungrarianCubeOperators())
     path = bfs(g,hungarianCubePredicate)
     
     for x in path:
         print x.data
         print "------"
     print "*&*&*&*&*&*&"
예제 #14
0
    def findBFS(self, start_name):
        g = load_graph()

        start = g[start_name]
        # Jasper: maybe change below line to make random?
        pref = self.preferences[0][0]

        end = g[str(pref)]
        path = bfs(start, end)
        return path
예제 #15
0
    def compute_details(self):  #this function is of little importance to the user.

	    #This function finds all non trivial details. This may include shortest distance to all powers and the first moves to be made to reach them in shortest time
    	#This can also compute other details like the area of the current region in which the bike resides etc..

    	self.player1 = bfs()
        self.player2 = bfs()
        self.player1.compute(self.map,self.my_posn)
        self.player2.compute(self.map,self.enemy_posn)
	
        self.n = len(self.player1.traverser_posn)

        for i in range(self.n):
	
            self.my_traverser_posn.append( self.player1.traverser_posn[i] )
            self.my_traverser_move.append( self.player1.traverser_move[i] )	
            self.my_traverser_distance.append( self.player1.traverser_distance[i] )
	
        self.m = len(self.player1.nitro_posn)

        for i in range(self.m):
	
            self.my_nitro_posn.append( self.player1.nitro_posn[i] )
            self.my_nitro_move.append( self.player1.nitro_move[i] )	
            self.my_nitro_distance.append( self.player1.nitro_distance[i] )
	
        self.p = len(self.player2.traverser_posn)

        for i in range(self.p):
	
            self.enemy_traverser_posn.append( self.player2.traverser_posn[i] )
            self.enemy_traverser_move.append( self.player2.traverser_move[i]	)
            self.enemy_traverser_distance.append( self.player2.traverser_distance[i] )
	
        self.q = len(self.player2.nitro_posn)

        for i in range(self.q):
	
            self.enemy_nitro_posn.append( self.player2.nitro_posn[i] )
            self.enemy_nitro_move.append( self.player2.nitro_move[i] )
            self.enemy_nitro_distance.append( self.player2.nitro_distance[i] )
예제 #16
0
 def findLunchPath(self, start_name):
     g = load_graph()
     
     start = g[start_name]
     # Jasper: maybe change below line to make random? 
     pref = self.preferences[0][0]
     
     end = g[str(pref)]
     path = bfs(start, end)
     
     # TRIP DISTANCE in pixels
     trip_dist = len(path)*39
     return trip_dist
예제 #17
0
    def findLunchPath(self, start_name):
        g = load_graph()

        start = g[start_name]
        # Jasper: maybe change below line to make random?
        pref = self.preferences[0][0]

        end = g[str(pref)]
        path = bfs(start, end)

        # TRIP DISTANCE in pixels
        trip_dist = len(path) * 39
        return trip_dist
예제 #18
0
def strategy_two(maze, fire, start, goal, q):
    fire_maze = np.copy(fire)
    temp_maze = np.copy(fire)
    dimension = maze.shape[0]
    temp_start = start

    curX = 0
    curY = 0

    while fire_maze[curX][curY] != 4:  # goal

        if fire_maze[curX][curY] == 7:  # runner is at a cell that is on fire
            return 'Died', fire_maze

        # calculate the path from the current cell to the goal at every step
        status, traversal_path, num_explored_nodes = bfs(
            temp_maze, temp_start, goal)

        if status == 'No Solution':  # the BFS call resulted in no path from the start to the goal being possible
            return 'No Path Possible', fire_maze

        # move to the next cell on the path
        if curX + 1 < dimension and (traversal_path[curX + 1][curY] == 6
                                     or traversal_path[curX + 1][curY] == 4):
            curX = curX + 1
        elif curY + 1 < dimension and (traversal_path[curX][curY + 1] == 6
                                       or traversal_path[curX][curY + 1] == 4):
            curY = curY + 1
        elif curX - 1 >= 0 and (traversal_path[curX - 1][curY] == 6
                                or traversal_path[curX - 1][curY] == 4):
            curX = curX - 1
        elif curY - 1 >= 0 and (traversal_path[curX][curY - 1] == 6
                                or traversal_path[curX][curY - 1] == 4):
            curY = curY - 1

        if fire_maze[curX][curY] == 4:  # goal is reached
            break

        fire_maze[curX][curY] = 6
        temp_start = (curX, curY)

        # advance the fire one step after the runner takes a step
        fire_maze = advance_fire_one_step(fire_maze, q)
        temp_maze = reset_path(
            fire_maze, dimension
        )  # allows BFS to let the runner go back up the current path if necessary

    return 'Escaped', fire_maze
예제 #19
0
def difference_explored(dimension, density):
    total_difference = 0

    for i in range(0, 100):
        maze_trial = generate_maze(dimension, density)  # generate maze
        status, maze_copy, num_explored_bfs = bfs(
            maze_trial, (0, 0),
            (dimension - 1,
             dimension - 1))  # run bfs and get number of explored nodes
        status, maze_copy, num_explored_astar = astar(
            maze_trial, (0, 0),
            (dimension - 1,
             dimension - 1))  # run A* and get number of explored nodes
        total_difference += (num_explored_bfs - num_explored_astar)

    return (total_difference / 100)
예제 #20
0
def strategy_one(maze, fire, start, goal, q):
    fire_maze = np.copy(fire)
    status, traversal_path, num_explored_nodes = bfs(
        fire_maze, start, goal
    )  # finds the shortest path from the start to the goal if one exists

    if status == 'No Solution':
        return 'No Path Possible', fire_maze

    dimension = maze.shape[0]

    curX = 0
    curY = 0

    while fire_maze[curX][
            curY] != 7:  # while the runner is not on a cell that is on fire
        if fire_maze[curX][
                curY] == 4:  # the runner has reached the goal and escaped successfully
            return 'Escaped', fire_maze

        if fire_maze[curX][curY] != 3:  # not the start
            fire_maze[curX][curY] = 6

        # calculate which cell is the next one on the path to the goal
        if curX + 1 < dimension and (traversal_path[curX + 1][curY] == 6
                                     or traversal_path[curX + 1][curY]
                                     == 4) and fire_maze[curX + 1][curY] != 6:
            curX = curX + 1
        elif curX - 1 >= 0 and (traversal_path[curX - 1][curY] == 6
                                or traversal_path[curX - 1][curY]
                                == 4) and fire_maze[curX - 1][curY] != 6:
            curX = curX - 1
        elif curY + 1 < dimension and (traversal_path[curX][curY + 1] == 6
                                       or traversal_path[curX][curY + 1] == 4
                                       ) and fire_maze[curX][curY + 1] != 6:
            curY = curY + 1
        elif curY - 1 >= 0 and (traversal_path[curX][curY - 1] == 6
                                or traversal_path[curX][curY - 1]
                                == 4) and fire_maze[curX][curY - 1] != 6:
            curY = curY - 1

        # after the runner has effectively moved to the above mentioned cell the fire must be advanced one step
        fire_maze = advance_fire_one_step(fire_maze, q)

    return 'Died', fire_maze
예제 #21
0
 def goToLunch(self, start_name, window):
      
     g = load_graph()
     
     start = g[start_name]
     
     pref = self.preferences[0][0]
     
     end = g[str(pref)]
     path = bfs(start, end)
     
     # TRIP DISTANCE in pixels
     trip_dist = len(path)*39
     
     
     '''
     prints shortest path in reverse
     # print the shortest path to students preference
     i = len(path) - 1
     print "Path for student: " + str(self)
     while (i >= 0):
         print path[i]
         i = i-1
     '''
     
     print " "
     print "Simulating Student " + str(self.id) + "'s shortest path to " + str(pref.name) + " from " + "(" + str(start_name) + ")"
     
     # important! index path BACKWARDS (shortest path is dict of BACKPOINTERS)
     i = len(path) - 1
     while (i > 0):
        
         print path[i].name
         
         if (i == 1):
             is_final = True
         else:
             is_final = False
             
         self.makeMove(path[i], path[i-1], is_final,window) 
         i = i-1
   
     print "Student arrived at destination "  + str(path[i].name) 
예제 #22
0
    def goToLunch(self, start_name, window):

        g = load_graph()

        start = g[start_name]

        pref = self.preferences[0][0]

        end = g[str(pref)]
        path = bfs(start, end)

        # TRIP DISTANCE in pixels
        trip_dist = len(path) * 39
        '''
        prints shortest path in reverse
        # print the shortest path to students preference
        i = len(path) - 1
        print "Path for student: " + str(self)
        while (i >= 0):
            print path[i]
            i = i-1
        '''

        print " "
        print "Simulating Student " + str(
            self.id) + "'s shortest path to " + str(
                pref.name) + " from " + "(" + str(start_name) + ")"

        # important! index path BACKWARDS (shortest path is dict of BACKPOINTERS)
        i = len(path) - 1
        while (i > 0):

            print path[i].name

            if (i == 1):
                is_final = True
            else:
                is_final = False

            self.makeMove(path[i], path[i - 1], is_final, window)
            i = i - 1

        print "Student arrived at destination " + str(path[i].name)
예제 #23
0
def test_path_algorithms():
    dimension = int(sys.argv[1])
    density = float(sys.argv[2])

    cmap = colors.ListedColormap(color_set)
    norm = colors.BoundaryNorm(range_set, len(color_set))
    plt.figure(figsize=(8, 8))
    plt.axis('off')

    maze = generate_maze(dimension, density)  # generate maze

    # run each algorithm on maze and time them
    start_time = time.time()
    status, astar_maze, num_explored_nodes = astar(
        maze, (0, 0), (dimension - 1, dimension - 1))
    end_time = time.time()
    print(status)
    print(end_time - start_time)
    print(num_explored_nodes)

    start_time = time.time()
    status, bfs_maze, num_explored_nodes = bfs(maze, (0, 0),
                                               (dimension - 1, dimension - 1))
    end_time = time.time()
    print(status)
    print(end_time - start_time)
    print(num_explored_nodes)

    start_time = time.time()
    status, dfs_maze = dfs(maze, (0, 0), (dimension - 1, dimension - 1))
    end_time = time.time()
    print(status)
    print(end_time - start_time)

    # plot each result and save as image
    plt.imshow(astar_maze, cmap=cmap, norm=norm)
    plt.savefig('astar_maze.jpg')

    plt.imshow(bfs_maze, cmap=cmap, norm=norm)
    plt.savefig('bfs_maze')

    plt.imshow(dfs_maze, cmap=cmap, norm=norm)
    plt.savefig('dfs_maze')
예제 #24
0
 def test_twoStepsHCube(self):
     cube = HungarianCube()
     print "original"
     node = Node(cube)
     print node.data
     print "*****"
     node = rotateFrontLeft(node)[0]
     print node.data
     print "*****"
     cube2 = rotateRightRight(node)[0].data
     print cube2
     print "*****"
     g = Graph(cube2,hungrarianCubeOperators())
     path = bfs(g,hungarianCubePredicate)
     self.assertEquals(len(path),3)
     print "Solution"
     print path[0].data
     print "-----"
     print path[1].data
     print "-----"
     print path[2].data
     print "-=-=-=-=-=-"
예제 #25
0
    def run_algorithm(self, algo):
        """
        Main algorithm function.
        :param algo: String, choosen algorithm
        :return: None
        """

        #Breadth-first search algorithm
        if algo == 'bfs':

            cf, hbxt = bfs(self.start_tile, self.end_tile)

        #Dijkstra's algorithm
        elif algo == 'dijkstra':
            cf, csf, hbxt = dijkstra(self.start_tile, self.end_tile)
            self.cost = csf[self.end_tile]

        #A* algorithm
        elif algo == 'a_star':
            cf, csf, hbxt = a_star(self.start_tile, self.end_tile)
            self.cost = csf[self.end_tile]

        self.draw_paths(cf, hbxt, algo)
예제 #26
0
from bfs import *
from dfs import *
from ids import *

# Code from this exercise all made by @skdGT

print("---- BFS -----")
node, tree = bfs(State1((0, 0), (0, 0), "Start"), goal=2)
print("- Tree -")
tree.print_tree()
if node is not None:
    path = find_path(node)
    print("- Solution -")
    print_path(path)
else:
    print("- No Solution -")
print('\n\n\n\n\n\n')

print("---- DFS -----")
node, tree = dfs(State1((0, 0), (0, 0), "Start"), max_depth=10)
print("- Tree -")
tree.print_tree()
if node is not None:
    path = find_path(node)
    print("- Solution -")
    print_path(path)
else:
    print("- No Solution -")

print('\n\n\n\n\n\n')
print("---- IDDFS -----")
예제 #27
0
from bfs import *
from dfs import *
from greedy import *
from astar import *
from ac3 import *
from backtracking import *
from sudoku import *

if __name__ == '__main__':
    # Lendo argumentos:
    filename = sys.argv[1]
    algorithm = sys.argv[2]

    if algorithm == "bfs":
        for board in read_board(filename):
            print(bfs(board))
    elif algorithm == "dfs":
        for board in read_board(filename):
            print(dfs(board))
    elif algorithm == "greedy":
        for board in read_board(filename):
            print(greedy(board, h1))
    elif algorithm == "astar":
        for board in read_board(filename):
            print(astar(board, g, h1))
    elif algorithm == "ac3":
        for board in read_board(filename):
            csp = CSP(board)
            print(AC3(csp, csp.queue()))
    elif algorithm == "backtracking":
        for board in read_board(filename):
예제 #28
0
from bfs import *
from maze import *
import sys

if __name__ == '__main__':

    m = Maze(20, 10)
    print(m)
    MazeNode.quiet_mode = False

    nodes = m.get_node_list()

    g = Graph()
    for i in nodes:
        # add each maze nodes edges to graph
        if i.u: g.add_edge(i.u, i.u.d)
        if i.d: g.add_edge(i.d, i.d.u)
        if i.l: g.add_edge(i.l, i.l.r)
        if i.r: g.add_edge(i.r, i.r.l)

    pprint(g)

    source_node = m.get(0, 0)

    bfs_result = bfs(g, source_node)

    pprint(bfs_result)

    print(m)
예제 #29
0
def findWordLadder(startWord, endWord, wordGraph):
    bfs(wordGraph, wordGraph.getNode(startWord))
    wl = extractWordLadder(wordGraph.getNode(startWord), wordGraph.getNode(endWord))
    return wl
예제 #30
0
import argparse
from bfs import *
from Algorithm_A import *

if __name__ == "__main__":
    parser = argparse.ArgumentParser(prog='main.py')
    parser.add_argument('--a',
                        help='insertion sort algorithm',
                        dest='a',
                        action="store_true")
    parser.add_argument('--bfs',
                        help='Bubble sort algorithm',
                        dest='bfs',
                        action="store_true")
    parser.add_argument('--start',
                        help='start point',
                        type=int,
                        nargs="+",
                        dest='start')
    parser.add_argument('--end',
                        help='start point',
                        type=int,
                        nargs="+",
                        dest='end')
    args = parser.parse_args()
    print(args)
    if args.a:
        a(args.start, args.end)
    if args.bfs:
        bfs(args.start, args.end)
예제 #31
0
pygame.init()
win = pygame.display.set_mode((width, height))
icon = pygame.image.load('icon.png')
pygame.display.set_icon(icon)
pygame.display.set_caption('Maze')
win.fill(white)
pygame.display.update()

# Рисуем лабиринт
new_maze()
kruskal()
# Выход
a[n + 2][m + 1] = a[n + 3][m + 1] = 0

# Максимальный путь
max_i, max_j = max_cell(bfs())
a[max_i][max_j] = 5
update()  # <<<---

# Рисуем кнопки + Получаем список всех кнопок
bs = draw_buttons()

# Рисуем игроков
for i in range(players):
    draw_player(0, 0, i)

while not end:
    pygame.time.delay(75)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
예제 #32
0
	exitonclick()

	
	

elif( option == 2):
	
	numNodes= [0]

	print( "Room is:")
	for i in range(size):
		print( initState[0][i])

	print("Position of vacuum cleaner is " + str( initState[1][0]) + ',' + str(initState[1][1]))	
	startTime = time.process_time()
	bfs( initState, path1, size, numNodes)
	totalTime = time.process_time() - startTime

	nodeSize = len(path1) + ( size*size ) + 2 
	totalCost = int((percentage * size * size)/100) + 2*len(path1) 

	print( "totalCost is " + str(totalCost))
	print( "Number of nodes created are " + str(numNodes))
	print( "Time taken " + str(totalTime))
	print("Node size is " + str(nodeSize))
	print( "Path is:")
	print(path1)
	
elif( option ==3):
	
	numNodes=[0]
예제 #33
0
from DirtGenerator import dirtGenerator
from dfs import *
from bfs import *

#initState = dirtGenerator(10)
initState = ([[0 for i in range(10)] for j in range(10)], [0,0])
initState[1][1] = 1
initState[1][0] = 1
initState[0][1][3] =1 
for i in range(10):
	print (initState[0][i])

print("position is " + str( initState[1][0]) + ',' + str(initState[1][1]))
		
path = []
bfs( initState, path)
print(path) 



예제 #34
0
from bfs import *
from graph import *
from vertex import *

g = Graph()

g.addVertex(4)
g.addVertex(7)
g.addVertex(55)
g.addVertex(12)
g.addVertex(54)

g.addEdge(4,7, "A")
g.addEdge(7,55 , "B")
g.addEdge(55,12, "C")
g.addEdge(12,54, "D")

g.addEdge(7,4, "A")
g.addEdge(55,7, "B")
g.addEdge(12,55, "C")
g.addEdge(54,12, "D")

bfs(g, 4)
예제 #35
0
 def test_simpleHungarianCube(self):
     cube = HungarianCube()
     g = Graph(cube,hungrarianCubeOperators())
     path = bfs(g,hungarianCubePredicate)
     self.assertEquals(map(lambda x: x.data, path),[cube])
예제 #36
0
def wordLadders(wordsFile="words5.text"):
    # 1. read the words file
    # 2. build a graph based on the words file
    # 3. user interaction loop:
    #    - request user to enter either two words (start and end word)
    #      or one word (start word) or 'q' (to quit)
    #    - check that the give word or words are in the dictionary
    #    - execute breadth first search from the start word's node
    #      (Note: you need to slightly modify the original bfs in bfs.py
    #      to set and update distance and parent properties of Nodes.  This also
    #      requires modification of the Node class in basicgraph.py to add
    #      those properties.)
    #    - if an end word was given, extract word ladder from
    #      start to that endword
    #    - if an end word was not given, find the node in the graph
    #      with the largest distance value and extract the ladder between
    #      the start node and that node.
    #    - print appropriate information - the extracted ladder and its length

    # code for 1. and 2. above goes here
    graph, nodes, edges = buildWordGraph(wordsFile)
    # code for 3. goes inside the while loop below
    print("Created word graph with " + str(nodes) + " nodes and " +
          str(edges) + " edges")
    userInput = input(
        "Enter start and end words OR start word OR 'q' to quit: ")
    words = userInput.split()

    while (words[0] != 'q'):
        wordsLen = len(words)
        counter = 0
        for x in words:
            for node in graph.nodes:
                if (node.getName() == "['" + str(x) + "']"):
                    counter = counter + 1

        if (wordsLen == counter):
            bfs(graph, graph.getNode("['" + words[0] + "']"))
            if (wordsLen == 1):
                maximumNum = 0
                for node in graph.nodes:
                    if node.getDist() >= maximumNum:
                        maximumNode = node
                        maximumNum = node.getDist()
                lad, dist = extractWordLadder(
                    graph.getNode(maximumNode.getName()))
                print(maximumNode.getName() + " is maximally distant (" +
                      str(dist) + " steps) from " + words[0])
                print(lad)
            if (wordsLen == 2):
                lad, dist = extractWordLadder(
                    graph.getNode("['" + words[1] + "']"))
                print("Shortest ladder from " + words[0] + " to " + words[1] +
                      " is length " + str(dist) + ":")
                print(lad)

        else:
            print("Word/Words are not in dictionary")

        userInput = input(
            "Enter start and end words OR start word OR 'q' to quit: ")
        words = userInput.split()
예제 #37
0
 def test_path_found1(self):
     path = ['s', 'e', 'r', 'f', 'g']
     self.assertEqual(bfs('s', 'g', self.g1), path)
예제 #38
0
파일: route.py 프로젝트: cocosci/SAMPLECODE
from sys import argv
#import all the objects in initGraph, not just import initGraph
from initGraph import *
#from bfs import *
from bfs import *
from dfs import *
from astar import *
from datetime import datetime
startTime = datetime.now()

# the arguments from user inputs.
script,	city1, city2, routingopt, algoopt= argv

#print G.node[city1]
#print G.node[city2]

# 'is' is to test if the two object is exactly the same,
# while == is for the testing of the value of stings themselves.
if algoopt == 'bfs':
	bfs(city1,city2,routingopt)
elif algoopt == 'dfs':
	dfs(city1,city2,routingopt)
elif algoopt == 'astar':
	astar(city1,city2,routingopt)
else:
	print 'Only bfs, dfs, and astar are supported!'
	#print algoopt

print 'Run time: %s'%(str(datetime.now() - startTime))
print '=================================================================='
예제 #39
0
from bfs import *
from dfs import *
from ids import *

# Code from this exercise all made by @skdGT

print("---- BFS -----")
node, tree = bfs(State2((3, 3, 1), (3, 3, 1), "Start"))
print("- Tree -")
tree.print_tree()
if node is not None:
    path = find_path(node)
    print("- Solution -")
    print_path(path)
else:
    print("- No Solution -")

print('\n\n\n\n\n\n')

print("---- DFS -----")
node, tree = dfs(State2((3, 3, 1), (3, 3, 1), "Start"))
print("- Tree -")
tree.print_tree()
if node is not None:
    path = find_path(node)
    print("- Solution -")
    print_path(path)
else:
    print("- No Solution -")
예제 #40
0
파일: main.py 프로젝트: gquintela/bfs
from bfs import *

# create dummy graph & driver test
my_graph = Graph()
my_graph.add_directed_edge('r', 's')
my_graph.add_directed_edge('t', 'u')
my_graph.add_directed_edge('w', 'x')
my_graph.add_directed_edge('x', 'y')
my_graph.add_directed_edge('r', 'v')
my_graph.add_directed_edge('s', 'w')
my_graph.add_directed_edge('t', 'x')
my_graph.add_directed_edge('u', 'y')
my_graph.add_directed_edge('t', 'w')
my_graph.add_directed_edge('u', 'x')

bfs_result = bfs(my_graph,'s')
print ("List of parents")
print(bfs_result[0])
print ("")

print ("List of distance from " + 's')
print(bfs_result[1])
print ("")

shortest_path(my_graph, 's', 'y')
예제 #41
0
def fs_tree(workflow_lines):
    """ gives the fs tree as view in workflow begin """
    w_lines_by_id = dict([(w_line._id,  w_line) for w_line in workflow_lines])

    def path_graph(dirs):
        """ ["/a/b/c", "/a/b", "/a"] -> {"/a":"/a/b", "/a/b":"/a/b/c"} """
        def pairwise(iterable):#this code is duplicated elsewhere
            a, b = tee(iterable)
            next(b, None)
            return izip(a, b)

        _graph = {}
        if len(dirs) == 1:
            _graph[dirs[0]] = None
        else:
            for (parent, child) in pairwise(reversed(dirs)):
                _graph[parent] = child
        return _graph

    def clean_call(line_id):
        w_line = w_lines_by_id[line_id]
        return w_line.clean_call

    parents_to_children = {}
    created_paths = set()

    the_graph = graph(workflow_lines)

    #FIMXE this code does not add fake root to orphan nodes. so, bfs does not work properly.
    #so, it is a hack to add the fake root
    num_nodes = len(workflow_lines)
    orphan_nodes = set(range(1, num_nodes + 1))#at the begin we think everyone is a orphan

    for father, children in the_graph.iteritems():
        for child in children:
            if child in orphan_nodes:
                orphan_nodes.remove(child)

    #adding fake root
    fake_root_id = 0
    the_graph[fake_root_id] = []
    for orphan in orphan_nodes:
        the_graph[fake_root_id].append(orphan)

    #NOTE: there is a corner case when handling open calls wiht O_CREAT flags, it's
    #possible to know if the a proper creation or a ordinary open because posix
    #allows one to call open with O_CREAT to a already created file. So, instead of
    #complicate things other methods (accessed_and_created), we are going to evaluate
    #open calls separately.

    #files we are sure were open using O_CREAT but were created before
    false_positive_ocreat = set()
    #files we cannot answer if they were created before open(O_CREAT)
    undefined_ocreat = set()
    #files we are trying to check if they were created before or not
    opentocreat_candidates = set()

    for node_and_child in bfs(the_graph, 0):
        child_id = int(node_and_child[1])
        if (child_id == 0):
            continue#argg
        node_clean_call = clean_call(child_id)

        if node_clean_call.call == "read" or \
            node_clean_call.call == "llseek":
            fullpath = node_clean_call.fullpath()
            if fullpath in opentocreat_candidates:
                #a path that receives a read or llseek beyond
                #its position 0 before any write call should
                #have been created before.
                if long(node_clean_call.rvalue) > 0:
                    false_positive_ocreat.add(fullpath)
                    opentocreat_candidates.remove(fullpath)
        elif node_clean_call.call == "write":
            fullpath = node_clean_call.fullpath()
            if fullpath in opentocreat_candidates:
                #so, a file opened using O_CREAT flag receives a write
                #we cannot decide if it is a false positive
                opentocreat_candidates.remove(fullpath)
                undefined_ocreat.add(fullpath)
        elif node_clean_call.call == "open":
            fullpath = node_clean_call.fullpath()
            if open_to_create(node_clean_call) and \
                not (fullpath in false_positive_ocreat) and \
                not (fullpath in undefined_ocreat):
                    opentocreat_candidates.add(fullpath)

    #It's possible to think directories are files, because they can be opened
    #or llseeked for example. So, we collected things we know are directories
    #during bfs walk, and do a check against the things we think are files but are not
    known_dirs = set()

    for node_and_child in bfs(the_graph, 0):
        child_id = int(node_and_child[1])
        if (child_id == 0):
            continue#argg

        node_clean_call = clean_call(child_id)
        ac_dirs, ac_files, c_dirs, c_files = accessed_and_created(node_clean_call)

        if (node_clean_call.call == "open") and open_to_create(node_clean_call):
            if node_clean_call.fullpath() in false_positive_ocreat:
                try:
                    if node_clean_call.fullpath() in c_files:
                        c_files.remove(node_clean_call.fullpath())
                except ValueError:
                    sys.stderr.write(node_clean_call.fullpath())
                    sys.exit(1)
                ac_files.append(node_clean_call.fullpath())

        for _dir in ac_dirs:
            known_dirs.add(_dir)
        for _dir in c_dirs:
            known_dirs.add(_dir)

        for c_dir in c_dirs:
            created_paths.add(c_dir)
        for c_file in c_files:
            created_paths.add(c_file)

        for parent_dir, child_dir in path_graph(ac_dirs).iteritems():
            if not parent_dir in created_paths:
                if not (parent_dir, "d") in parents_to_children:
                    parents_to_children[(parent_dir, "d")] = set()
                if child_dir:
                    if not child_dir in created_paths:
                        parents_to_children[(parent_dir, "d")].add((child_dir, "d"))

        for a_file in ac_files:
            if not a_file in created_paths:
                parent = parent_path(a_file)
                if not (parent, "d") in parents_to_children:
                    parents_to_children[(parent, "d")] = set()
                parents_to_children[(parent, "d")].add((a_file, "f"))

    #accessed_and_created method is not reliable, for example
    #it is possible to directories be opened and closed, also llseeked
    #for this reason, ac_files can return directories, to get over it
    #we make a second pass to see if an acessed file was also identified as
    #directory, if so, we change its type
    #TODO is the conversely possible ? think a file is a directory
    to_change_type = []
    for parent, children in parents_to_children.iteritems():
        for path, _type in children:
            if _type is "f":
                if path in known_dirs:
                    to_change_type.append((parent, (path, _type)))

    for parent, child in to_change_type:
        parents_to_children[parent].remove(child)
        parents_to_children[parent].add((child[0], "d"))

    return parents_to_children
예제 #42
0
def kevinbaconnumber(actor):
    actors = open("actors.txt","r")
    movies = open("movies.txt","r")
    movieactors = open("movieactors.txt","r")

    actordic = {}
    actorlist = []
    for aline in actors:
        actorlist = aline.split("|")
        editactor = actorlist[1].replace("\n","")
        actordic[int(actorlist[0])] = editactor

    actors = open("actors.txt","r")
    revactordic = {}
    revactorlist = []
    for aline in actors:
        revactorlist = aline.split("|")
        editactorrev = revactorlist[1].replace("\n","")
        revactordic[editactorrev] = int(revactorlist[0])

    moviedic = {}
    movielist = []
    for aline in movies:
        movielist = aline.split("|")
        editmovie = movielist[1].replace("\n","")
        moviedic[int(movielist[0])] = editmovie

    madic = {}
    malist = []
    for aline in movieactors:
        malist = aline.split("|")
        editma = malist[1].replace("\n","")
        if int(malist[0]) in madic:
            madic[int(malist[0])].append(int(editma))
        else:
            madic[int(malist[0])] = []
            madic[int(malist[0])].append(int(editma))
            

    kbg = Graph()
    actors = open("actors.txt","r")
    actorlist = []
    for aline in actors:
        actorlist = aline.split("|")
        kbg.addVertex(int(actorlist[0]))
        

    movies= open("movieactors.txt","r")
    movielist = []
    for aline in movies:
        movielist = aline.split("|")
        movienum = int(movielist[0])
        edges = madic[movienum]
        while len(edges) >= 1:
            for i in range(len(edges)-1):
                kbg.addEdge(edges[0],edges[i+1],movienum)
                kbg.addEdge(edges[i+1],edges[0],movienum)
            edges.pop(0)

    bfs(kbg,63)

    if actor in revactordic:
        if kbg.getVertex(revactordic[actor]).getDistance() > 2000:
            print("This actor is not related to Kevin Bacon")
        else:
            vert = kbg.getVertex(revactordic[actor])
            print("Kevin Bacon Number:",vert.getDistance())
            actornum = revactordic[actor]
            while actornum != 63:
                nextactor = kbg.getVertex(actornum).getPred()
                commonmovie = kbg.getVertex(actornum).getCost(nextactor)
                print(actordic[actornum],"was in",moviedic[commonmovie],"which also starred")
                actornum = nextactor.getId()
            print("Kevin Bacon")
    else:
        print("This actor is not in our database (check spelling)")
예제 #43
0
 def test_path_target_not_found1(self):
     path = []
     self.assertEqual(bfs('s', 'z', self.g1), None)
예제 #44
0
from mst import *
from sp import *

# BFS
s = 8
edges = [(0, 1, None),
         (0, 2, None),
         (2, 3, None),
         (3, 4, None),
         (3, 5, None),
         (4, 5, None),
         (4, 6, None),
         (5, 7, None),
         (6, 7, None)]
g = Graph(0, s, edges)
assert(bfs(g, 0) == [0, 1, 2, 3, 4, 5, 6 ,7])

# DFS
assert(dfs(g, 0) == [0, 1, 2, 3, 4, 5, 7, 6])

# Topological Sort 
s = 9
edges = [(0, 1, None),
         (0, 4, None),
         (1, 2, None),
         (1, 4, None),
         (2, 7, None),
         (3, 4, None),
         (5, 2, None),
         (5, 6, None),
         (6, 7, None)]
예제 #45
0
 def test_path_infinite_loop(self):
     path = ['s', 'd', 'e', 'g']
     self.assertEqual(bfs('s', 'g', self.g2), path)
예제 #46
0
def wordLadders(wordsFile):
    global wordGraph  # this is useful for debugging - you can "look" at wordGraph
    # in the Python shell to determine if it's correct

    # 1. read the words file and build a graph based on the words file
    wordGraph = buildWordGraph(wordsFile)
    print("Created word graph with {} nodes and {} edges".format(
        len(wordGraph.nodes),
        sum(len(adjList)
            for adjList in wordGraph.adjacencyLists.values()) // 2))

    #    - check that the give word or words are in the dictionary
    #    - execute breadth first search from the start word's node
    #      (Note: you need to slightly modify the original bfs in bfs.py
    #      to set and update distance and parent properties of Nodes.  This also
    #      requires modification of the Node class in basicgraph.py to add
    #      those properties.)
    #    - if an end word was given, extract word ladder from
    #      start to that endword
    #    - if an end word was not given, find the node in the graph
    #      with the largest distance value and extract the ladder between
    #      the start node and that node.
    #    - print appropriate information - the extracted ladder and its length

    # 2. user interaction loop:

    userInput = input(
        "Enter start and end words OR start word OR 'q' to quit: ")
    words = userInput.split()
    while (words[0] != 'q'):

        # make sure word or words are in the wordsFile (and thus now in graph)
        startNode = wordGraph.getNode(words[0])
        if (startNode is None):
            print(
                "The start word is not in the dictionary.  Please try again.")
        elif (len(words) == 2) and (wordGraph.getNode(words[1]) is None):
            print("The end word is not in the dictionary.  Please try again.")
        elif (len(words) == 2) and (words[0] == words[1]):
            print(
                "The start and end words must be different. Please try again.")
        else:

            # Execute bread-first search from the startNode.  This
            # should set distance properties of all words reachable from start
            # word, and also set "parent" properties appropriately.
            bfs(wordGraph, startNode)

            # If only one word was given, look through all nodes in the graph
            # to find one with max distance property. That word is the one with
            # the maximal "shortest distance" from start word.
            if (len(words) == 1):
                maxDistance = -1
                for node in wordGraph.nodes:
                    dist = node.getDistance()
                    if dist is not None and dist >= maxDistance:
                        endNode = node
                        maxDistance = node.getDistance()
                print("{} is maximally distant ({} steps) from {}:".format(
                    endNode.getName(), maxDistance, words[0]))

            # If two words were given, execute extractWordLadder from node for
            # second word, yielding a list of words representing the shortest
            # path between start and end words.
            else:
                endNode = wordGraph.getNode(words[1])
                if endNode.getParent() == None:
                    print("There is no word ladder from ", startNode.getName(),
                          " to ", endNode.getName())
                else:
                    print("Shortest ladder from {} to {} is length {}:".format(
                        words[0], words[1], endNode.distance))
            ladder = extractWordLadder(endNode)
            for word in ladder:
                print(word, end=" ")
            print()

        # Finally, ask for new start/end or start words or 'q'
        userInput = input(
            "Enter start and end words OR start word OR 'q' to quit: ")
        words = userInput.split()
예제 #47
0
from eight import state
from bfs import *
from timeit import Timer

initial = state(None, [8,1,3,2,4,5,state.space,7,6], 0)
goal = state(None, [1,2,3,8,state.space,4,7,6,5])

print(initial)

f = lambda: bfs(initial, goal)          

res = f()        
print('has decision  :', res[0])    
print('open states   :', res[2])    
print('closed states :', res[3])        
print('result path   :')    
for m in res[1]:
    print(m)
    
t = Timer(f)
print("Time = ", t.timeit(number=100))
예제 #48
0
from init_database import *
from database_functions import *
from bfs import *

if __name__ == '__main__':
    #create_info_table()
    #create_links_table()
    print('\n'.join(bfs('Minecraft', 'Gamecube')))
예제 #49
0
for row in con:
    i = row[0]
    j = row[1]
    d = row[2]
    distance_matrix[i][j] = d
    distance_matrix[j][i] = d


#get a adjacency list

networklist = [[] for i in range(n)]

for row in con:
    i = row[0]
    j = row[1]
    d = row[2]
    networklist[i].append(j)
    networklist[j].append(i)
    


bfs_test = bfs(networklist,2)
dfs_test = dfs(networklist,2)

print('Verticed for bfs: ',bfs_test)
print('Vertices for dfs: ',dfs_test)

#Results:
#Verticed for bfs:  [2, 1, 5, 3, 0, 4, 7, 6]
#Vertices for dfs:  [2, 3, 7, 6, 4, 0, 5, 1]
예제 #50
0
 def test_bfs(self):
     g = Graph('a',[op2])
     path = bfs(g,goal_predicate1)
     self.assertFalse(path is None)
     self.assertTrue(['a', 'c', 'd'] == map(lambda x: x.data, path) or \
                     ['a', 'b', 'd'] == map(lambda x: x.data, path))