예제 #1
0
def TimSort(arr):
    
    i = 0
    runs = queue()
    while i < len(arr):
        start,end = ascending(arr,i)
        if start == end:
            start,end = descending(arr,i)
            reverse(arr,start,end)
            
        runs.insert((start,end))
        print("insert the queue: ",(start,end))
        i = end+1
    
    while runs.not_empty():
        run1 = runs.pop()
        run2 = runs.pop()

        if run1 and run2:

            if run1 > run2:
                runs.insert(run1)
                run1 = runs.pop()
                run1,run2 = run2,run1

            start,middle = run1
            s2,end = run2
            print("Merge:" ,(start,middle),(s2,end))
            Merge(arr,start,middle,end)
            runs.insert((start,end))
def BFS(i, j, color):
    fila = queue()
    fila.insert((i, j))
    paint_position(screen, i, j, color, show=True)
    while fila.not_empty():
        i, j = fila.pop()
        if ((i + 1 < ROWS) and grid[i + 1][j] != Black
                and grid[i + 1][j] != color):
            paint_position(screen, i + 1, j, color, show=True)
            fila.insert((i + 1, j))
        if ((0 < i) and grid[i - 1][j] != Black and grid[i - 1][j] != color):
            paint_position(screen, i - 1, j, color, show=True)
            fila.insert((i - 1, j))
        if ((j + 1 < COLS) and grid[i][j + 1] != Black
                and grid[i][j + 1] != color):
            paint_position(screen, i, j + 1, color, show=True)
            fila.insert((i, j + 1))
        if ((j > 0) and grid[i][j - 1] != Black and grid[i][j - 1] != color):
            paint_position(screen, i, j - 1, color, show=True)
            fila.insert((i, j - 1))
예제 #3
0
def BFS(i, j):
    fila = queue()
    fila.insert((i, j))
    while fila.not_empty():
        i, j = fila.pop()
        if ((i + 1 < ROWS) and (grid[i + 1][j] == White)):
            grid[i + 1][j] = Lime
            just_paint(screen, j, i + 1, Lime)
            fila.insert((i + 1, j))
        if ((0 < i) and (grid[i - 1][j] == White)):
            grid[i - 1][j] = Lime
            just_paint(screen, j, i - 1, Lime)
            fila.insert((i - 1, j))
        if ((j + 1 < COLS) and (grid[i][j + 1] == White)):
            grid[i][j + 1] = Lime
            just_paint(screen, j + 1, i, Lime)
            fila.insert((i, j + 1))
        if ((j > 0) and (grid[i][j - 1] == White)):
            grid[i][j - 1] = Lime
            just_paint(screen, j - 1, i, Lime)
            fila.insert((i, j - 1))
예제 #4
0
def BFS(i, j, color):
    fila = queue()
    fila.insert((i, j))
    color_bfs = Dark_yellow
    while fila.not_empty():
        i, j = fila.pop()
        if ((i + 1 < ROWS) and grid[i + 1][j] == color):
            grid[i + 1][j] = color_bfs
            paint_position(screen, i + 1, j, grid[i + 1][j], show=True)
            fila.insert((i + 1, j))
        if ((0 < i) and grid[i - 1][j] == color):
            grid[i - 1][j] = color_bfs
            paint_position(screen, i - 1, j, grid[i - 1][j], show=True)
            fila.insert((i - 1, j))
        if ((j + 1 < COLS) and grid[i][j + 1] == color):
            grid[i][j + 1] = color_bfs
            paint_position(screen, i, j + 1, grid[i][j + 1], show=True)
            fila.insert((i, j + 1))
        if ((j > 0) and grid[i][j - 1] == color):
            grid[i][j - 1] = color_bfs
            paint_position(screen, i, j - 1, grid[i][j - 1], show=True)
            fila.insert((i, j - 1))
예제 #5
0
def kruskanimatedfs(graph,node_position, steps_mode = False):

    from math import hypot
    from algorithms.data_struct.UnionFind import UnionFind
    from algorithms.data_struct.queue import queue
    import pygame,time
    
    Black	        =	    (0,0,0)
    White	        =	    (255,255,255)
    Red  	        =	    (255,0,0)
    Dark_red        =     	(150,0,0)
    Lime	        =	    (0,255,0)
    Blue	        =	    (0,0,200)
    Yellow	        =	    (255,255,0)
    Dark_yellow     =       (250,200,0)
    Flame           =       (226,88,34)
    Cyan 	        =	    (0,255,255)
    Magenta	        =	    (255,0,255)
    Gray	        =	    (128,128,128)
    Dark_gray       =       (50, 50, 50)
    Maroon 	        =	    (128,0,0)
    Olive  	        =	    (128,128,0)
    Green  	        =	    (0,180,0)
    Purple 	        =	    (128,0,128)
    Teal	        =	    (0,128,128)
    Navy	        =	    (0,0,128)
    Light_sky       = 		(135,206,250)
    Castanho	    =	    (165,42,42)
    Carmesim	    =	    (220,20,60)
    Cream           =	    (245,255,250)
    Some_grey       =       (112,128,144)
    Light_grey      =       (119,136,153)
    Melada	        =       (240,255,240)
    Orange	        =       (255,165,0)
    Springgreen	    =       (0,255,127)
    Dark_grey       =       (41,41,41)
    skyblue	        =       (135,206,235)
    deepskyblue	    =       (0,191,255)
    lightsteelblue	=       (176,196,222)
    dodgerblue	    =       (30,144,255)
    cornflowerblue	=       (100,149,237)
    steelblue	    =       (70,130,180)
    cadetblue	    =       (95,158,160)
    mediumslateblue	=       (123,104,238)
    royalblue   	=       (65,105,225)

    
    list_colors = [
        Purple 	        ,
        Some_grey       ,
        Carmesim	    ,
        Lime            ,
        royalblue       ,
        Light_grey      , 
        skyblue	        ,
        Dark_gray       ,
        Maroon 	        ,
        Olive  	        ,
        Green  	        ,  
        deepskyblue	    ,
        Dark_red        ,
        Light_sky       ,
        Castanho	    ,        	
  	    Cyan 	        ,
        Springgreen	    ,
        Flame           ,
        Magenta	        , 	
        Gray	        ,  
        Yellow	        ,
        Orange	        ,
        Teal	        ,
        Melada	        , 
        Cream           ,
        lightsteelblue	,  
        dodgerblue	    ,  
        cornflowerblue	,  
        steelblue	    ,  
        cadetblue	    ,  
        mediumslateblue	,  
        Dark_yellow     ,
    ]
    SP = 0

    node_radius       = 5
    node_color        = Blue
    cur_edge_color    = Green
    choose_edge_color = Cyan
    not_choosen_color = Black

    number_size = 12
    weight_color = Cyan
    memory_color = Red
    current_color = Lime
    visited_color = Cyan
    
    screen_height = 700
    screen_width = 1200
    screen = pygame.display.set_mode((screen_width,screen_height))
    screen.fill((0,0,0))

    pygame.init()

    disjoint_set = UnionFind(len(graph))
    edge_list = []
    set_color = list( list_colors[x%len(list_colors)] for x in range(len(graph)))
    
    #functions
    def distance(node1,node2):
        return int(hypot(node1[0]-node2[0], node1[1]-node2[1]))   




    font = pygame.font.Font('freesansbold.ttf',number_size)


    for node in range(len(graph)):
        for neighbour in graph[node]:
            node1 = node_position[node]
            node2 = node_position[neighbour]
            pygame.draw.line(screen,Dark_grey, node1, node2,1)
    
    #draw circles (nodes)
    for node_number in range(len(graph)):                                                          # draw nodes
            pygame.draw.circle(screen, node_color, node_position[node_number], node_radius)
    
    pygame.display.update()




    #show information
    font = pygame.font.Font('freesansbold.ttf',30)
    text = font.render("Kruskal ",True,Cyan)                        
    screen.blit(text,text.get_rect(center = (1050,70)))
    text = font.render("animated",True,Cyan)                        
    screen.blit(text,text.get_rect(center = (1050,100)))
    text = font.render("with BFS",True,Cyan)                        
    screen.blit(text,text.get_rect(center = (1050,140)))


    pygame.display.update()

    time.sleep(1)

    edge_dict = {}


    font = pygame.font.Font('freesansbold.ttf',number_size-1)
    for node1 in range(len(graph)):
        for node2 in graph[node1]:
            weight = distance(node_position[node1], node_position[node2])
            if (weight,node2,node1) in edge_list: continue
            edge_list.append((weight,node1, node2))
    


    time.sleep(1)

    font = pygame.font.Font('freesansbold.ttf',25)
    text = font.render("Sort edges",True,Cyan)                        
    screen.blit(text,text.get_rect(center = (1100,250)))
    pygame.display.update()

    time.sleep(1)

    pygame.draw.rect(screen,Black,(1000,230,200,100))
    edge_list.sort()


    font = pygame.font.Font('freesansbold.ttf',30)
    text = font.render("edges",True, Black)                        
    screen.blit(text,text.get_rect(center = (780,20)))

    # animation loop
   
    edge_id = 0
    N_edge_MST = 0

    pause = False
    while True:

        
            # pygame stuff:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()                   #exit pygame,
                quit()                          #exit() program


            
            if event.type == pygame.KEYDOWN:        
                if event.key == pygame.K_SPACE:     #press breakspace to pause or play
                    pause = not pause   
                    time.sleep(0.2)

        if pause:
            continue

        if N_edge_MST == len(graph)-1:
            if  edge_id == len(edge_list):
                continue
            _,node1,node2 = edge_list.pop(edge_id)
            edge_id+1
            
                   
            pygame.draw.line(screen,Black,node_position[node1], node_position[node2],2)
            pygame.display.update()
            time.sleep(0.003)
            continue



        weight,node1,node2 = edge_list[edge_id]
        pygame.draw.line(screen,cur_edge_color,node_position[node1], node_position[node2],2)

        pygame.display.update()        
        if not pause: time.sleep(0.1) 

        if disjoint_set.Find(node1) != disjoint_set.Find(node2):
            pygame.draw.line(screen,choose_edge_color,node_position[node1], node_position[node2],5)            

            
            Patriarch1 = disjoint_set.Find(node1)
            Patriarch2 = disjoint_set.Find(node2)
            Q = queue()
            seen = list(False for _ in range(len(graph)))
            Q.insert(node1)
            
            seen[node1]=True
            
            while Q.not_empty():
                node = Q.pop()
                pos = node_position[node]
                set_color[node] = set_color[Patriarch2]
                pygame.draw.circle(screen,set_color[Patriarch2],pos,8)
                for neighbour in graph[node]:
                    if not seen[neighbour] and( disjoint_set.Find(neighbour) == Patriarch1 ):
                        Q.insert(neighbour)
                        seen[neighbour] = True     
                    pygame.display.update()
                    time.sleep(0.003)
            pygame.draw.circle(screen,set_color[node2],pos,8)

            disjoint_set.Union(node1,node2)
            pygame.draw.circle(screen,set_color[Patriarch2],node_position[node2],8)
            pygame.display.update()

            N_edge_MST += 1

           


        
        elif (node1,node2) not in edge_dict and (node2,node1) not in edge_dict:
            pygame.draw.line(screen,not_choosen_color,node_position[node1], node_position[node2],2)
            pygame.draw.circle(screen,set_color[node1],node_position[node1],8)
            pygame.draw.circle(screen,set_color[node2],node_position[node2],8)
            pygame.display.update()
            

        edge_dict[(node1,node2)] = True


     
        edge_id += 1
        if edge_id == len(edge_list) or  N_edge_MST == len(graph)-1:
            pause = True
예제 #6
0
def show_tree(delay=0.1):
    from algorithms.data_struct.queue import queue
    xL, yD, xR, yU = 10, 10, screen_width, screen_height
    vertical = False

    Q = queue()

    Q.insert((root, xL, yD, xR, yU, vertical))

    pause = False
    running = True
    while running:

        # pygame stuff:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()  #exit pygame,
                running = False  #exit() program

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    pause = not pause
                    time.sleep(0.2)

        if pause:
            continue

        if Q.not_empty():
            cur, xL, yD, xR, yU, vertical = Q.pop()
        else:
            if delay != 0: time.sleep(1)
            break

        print_point((cur.x, cur.y), (vertical) * Cyan + (not vertical) * Red,
                    radius=6,
                    show=(delay != 0))
        print_lines((cur.x, cur.y),
                    vertical,
                    xL,
                    yD,
                    xR,
                    yU,
                    show=(delay != 0))
        time.sleep(delay)

        if vertical == True:

            if cur.right:
                Q.insert((cur.right, xL, cur.y, xR, yU, not vertical))
                arrow(screen, (cur.x, cur.y), (cur.right.x, cur.right.y),
                      show=(delay != 0))

                time.sleep(delay / 2)
            if cur.left:
                Q.insert((cur.left, xL, yD, xR, cur.y, not vertical))
                arrow(screen, (cur.x, cur.y), (cur.left.x, cur.left.y),
                      show=(delay != 0))

                time.sleep(delay / 2)
        else:

            if cur.right:
                Q.insert((cur.right, cur.x, yD, xR, yU, not vertical))
                arrow(screen, (cur.x, cur.y), (cur.right.x, cur.right.y),
                      show=(delay != 0))

                time.sleep(delay / 2)
            if cur.left:
                Q.insert((cur.left, xL, yD, cur.x, yU, not vertical))
                arrow(screen, (cur.x, cur.y), (cur.left.x, cur.left.y),
                      show=(delay != 0))

                time.sleep(delay / 2)
import pygame, time
from threading import Thread, Lock, Condition
from random import randint
from algorithms.data_struct.queue import queue
from algorithms.data_struct.stack import stack
from algorithms.colors import *

mutex_stack = Lock()
mutex_ponto = Lock()
mutex_ponto = Condition()
mutex_display = Lock()
N_operantes = 0

Q = queue()

pygame.init()

screen_height = 700
screen_width = 1300
screen = pygame.display.set_mode((screen_width, screen_height))

screen.fill((0, 0, 0))
square_width = 3
space = 2
index_color = (0, 200, 0)
index2_color = (200, 200, 0)
numb_color = (50, 50, 250)
const_color = (255, 255, 255)
sum_color = (250, 250, 0)
duplicate_color = (255, 0, 0)
ground = 500
def cycleWith2Nodes(graph, node_position, s=0, t=1, steps_mode=False):
    from algorithms.colors import Dark_red, Flame, Cyan, White, Blue, royalblue, Black, Springgreen, Green, Lime, Cream, Dark_yellow, Yellow, skyblue
    from algorithms.data_struct.queue import queue
    from algorithms.data_struct.stack import stack

    pygame.init()

    screen_height = 700
    screnn_width = 1300
    screen = pygame.display.set_mode((screnn_width, screen_height))

    screen.fill((0, 0, 0))

    N = len(graph)  #number of nodes in the graph
    display_graph(screen, graph, N, node_position, s, t)

    for _ in range(N):
        graph.append([])

    for node in range(N):
        if node != s and node != t:
            for neighbour in graph[node]:
                graph[node + N].append(neighbour)
                graph[node] = [node + N]

    temp_list = graph[t]
    graph[t] = []
    for neighbour in temp_list:
        graph[t].append(neighbour + N)

    font = pygame.font.Font('freesansbold.ttf', 20)
    text = font.render("Find shortest cycle", True, Dark_yellow)
    screen.blit(text, text.get_rect(center=(950, 70)))

    text = font.render("with the 2 yellow nodes", True, Dark_yellow)
    screen.blit(text, text.get_rect(center=(950, 90)))

    pygame.draw.circle(screen, Cyan, (880, 450), 14)
    text = font.render("visited", True, Cyan)
    screen.blit(text, text.get_rect(center=(980, 450)))

    pygame.draw.circle(screen, skyblue, (880, 500), 12)
    text = font.render("sender in queue", True, skyblue)
    screen.blit(text, text.get_rect(center=(980, 500)))
    text = font.render("s", True, Flame)
    screen.blit(text, text.get_rect(center=(880, 500)))

    pygame.draw.circle(screen, Springgreen, (880, 550), 12)
    text = font.render("receiver in queue", True, Springgreen)
    screen.blit(text, text.get_rect(center=(980, 550)))
    text = font.render("r", True, Flame)
    screen.blit(text, text.get_rect(center=(880, 550)))

    pygame.draw.circle(screen, Lime, (880, 600), 14)
    text = font.render("current", True, Lime)
    screen.blit(text, text.get_rect(center=(980, 600)))

    pygame.display.update()
    time.sleep(3.5)

    # ALGORITHM STARTS HERE
    font = pygame.font.Font('freesansbold.ttf', 20)
    text = font.render("Split each not yellow node", True, White)
    screen.blit(text, text.get_rect(center=(950, 150)))
    pygame.display.update()
    time.sleep(2)
    text = font.render("in sender and receiver nodes", True, White)
    screen.blit(text, text.get_rect(center=(950, 170)))
    pygame.display.update()
    time.sleep(2.5)

    pygame.draw.rect(screen, Black, (0, 0, 800, 2000))
    display_graph(screen,
                  graph,
                  N,
                  node_position,
                  s,
                  t,
                  edges_animation=True,
                  first_display=False)
    pygame.draw.rect(screen, Black, (800, 130, 500, 200))
    time.sleep(1)

    predecessor = list(-1 for _ in range(2 * N))
    predecessor[s] = s
    flow_to = list(-1 for _ in range(2 * N))
    Q = queue()

    start = True
    bfs = True
    path = False
    cycle = False
    first_iteration = True

    pause = False
    while True:

        # pygame stuff:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()  #exit pygame,
                quit()  #exit() program

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:  #press breakspace to pause or play
                    pause = not pause
                    time.sleep(0.2)

        if pause:
            continue

        if steps_mode:  #pause every step of the algorithm
            pause = True  #when this iteration ends,the animation is paused

        if bfs:

            if start:

                font = pygame.font.Font('freesansbold.ttf', 20)
                if first_iteration:
                    text = font.render("First BFS", True, Cyan)
                else:
                    pygame.draw.rect(screen, Black, (800, 130, 500, 200))
                    text = font.render("Second BFS", True, Cyan)

                screen.blit(text, text.get_rect(center=(950, 150)))

                text = font.render("Searching augmenting path", True,
                                   royalblue)

                screen.blit(text, text.get_rect(center=(950, 170)))
                pygame.display.update()
                time.sleep(2.5)
                for neighbour in graph[s]:
                    Q.insert(neighbour)
                    predecessor[neighbour] = s
                    memorize(screen,
                             node_position[neighbour],
                             Time=0.05,
                             sender_on=False)
                start = False

            cur = Q.pop()
            visit(screen, node_position[cur % N], radius=14, Time=0.07)
            for neighbour in graph[cur]:
                if predecessor[neighbour] < 0:  # has not seen the node
                    Q.insert(neighbour)
                    predecessor[neighbour] = cur
                    memorize(screen,
                             node_position[neighbour % N],
                             Time=0.02,
                             sender_on=(neighbour >= N))

                    if neighbour == t:
                        bfs = False
                        path = True

                        pygame.draw.rect(screen, Black, (800, 130, 500, 200))
                        text = font.render("Found T", True, Dark_yellow)
                        screen.blit(text, text.get_rect(center=(950, 170)))
                        pygame.display.update()
                        time.sleep(2)
                        break

            mark(screen, node_position[cur % N], Black, radius=14, show=False)
            visited(screen, node_position[cur % N], radius=12, Time=0.02)
            if cur < N and flow_to[cur] < 0:
                change(screen, node_position[cur % N], Time=0.01)

        elif path:

            pygame.draw.rect(screen, Black, (800, 130, 500, 200))
            text = font.render("Update augmenting path", True, Dark_yellow)
            screen.blit(text, text.get_rect(center=(950, 170)))
            pygame.display.update()

            cur = t
            S = stack()

            path_edge_dict = {}

            while cur != s:
                pred = predecessor[cur]
                S.insert((pred, cur))  # insert to make a good animation latter
                path_edge_dict[(pred, cur)] = True

                #reverse edge
                graph[cur].append(pred)
                graph[pred].remove(cur)

                if flow_to[pred] == cur:  #counter flux
                    S.pop()
                    S.insert((-pred, -cur))
                else:
                    flow_to[cur] = pred

                cur = pred

            while S.not_empty():  # animation showing path
                node1, node2 = S.pop()
                if node1 < 0 or node2 < 0:
                    node1, node2 = -node1, -node2
                    pygame.draw.line(screen, Black, node_position[node1 % N],
                                     node_position[node2 % N], 5)
                    pygame.draw.line(screen, White, node_position[node1 % N],
                                     node_position[node2 % N], 1)
                    mark(screen, node_position[node1 % N], Blue, radius=14)
                    mark(screen, node_position[node2 % N], Blue, radius=14)
                    pygame.display.update()
                else:
                    arrow(screen, node_position[node1 % N],
                          node_position[node2 % N], Dark_yellow, Dark_red, 5,
                          5)
                    mark(screen, node_position[node1 % N], Blue, radius=14)
                time.sleep(0.05)

            if first_iteration == True:

                pygame.draw.rect(screen, Black, (0, 0, 2000, 2000))
                #print edges
                for node in range(2 * N):
                    for neighbour in graph[node]:
                        if ((neighbour, node) not in path_edge_dict) and (
                            (node, neighbour) not in path_edge_dict):
                            pygame.draw.line(screen, White,
                                             node_position[node % N],
                                             node_position[neighbour % N], 1)

                path_edge_dict = {}

                cur = t
                while cur != s:
                    pred = predecessor[cur]
                    pygame.draw.line(screen, Dark_yellow,
                                     node_position[cur % N],
                                     node_position[pred % N], 5)
                    cur = pred

                #print nodes
                for node in range(N):
                    mark(screen, node_position[node % N], Blue, 12, False)

                pygame.display.update()

                first_flow_to_t = flow_to[t]
                flow_to[t] = -1
                predecessor = list(-1 for _ in range(2 * N))
                predecessor[s] = s
                Q = queue()
                start = True

                first_iteration = False
                path = False
                bfs = True
                mark(screen, node_position[t], Dark_yellow, 14)
                mark(screen, node_position[s], Dark_yellow, 14)
                time.sleep(2)

            else:
                cycle = True
                path = False
                mark(screen, node_position[t], Dark_yellow, 14)
                mark(screen, node_position[s], Dark_yellow, 14)
                time.sleep(1.5)

        elif cycle:
            pygame.draw.rect(screen, Black, (800, 130, 500, 200))
            text = font.render("Shortest Cycle", True, Dark_yellow)
            screen.blit(text, text.get_rect(center=(950, 170)))
            pygame.display.update()
            #            cur = t
            #            S = stack()
            #            while cur != s:
            #                pred = flow_to[cur]
            #                S.insert((pred,cur))
            #                cur = pred
            #
            #            while S.not_empty():
            #                node1,node2 = S.pop()
            #                arrow(screen,node_position[node1%N],node_position[node2%N],Lime,Green,6,4)
            #                time.sleep(0.3)
            #
            #            cur = first_flow_to_t
            #            arrow(screen,node_position[t],node_position[cur%N])
            #            while cur != s:
            #                node2,node1 = flow_to[cur],cur
            #                arrow(screen,node_position[node1%N],node_position[node2%N],Lime,Green,6,4)
            #                cur = flow_to[cur]
            #                time.sleep(0.3)

            cycle = False
            pause = True
            if UF.Find((ROWS, 0)) == UF.Find((ROWS, 1)):
                paint_position(screen, x, y, Yellow, show=True)
                font = pygame.font.Font('freesansbold.ttf', 30)
                text = font.render("Percolated!", True, Yellow)
                screen.blit(text, text.get_rect(center=(1000, 200)))
                pygame.display.update()
                time.sleep(5)

                for i in range(ROWS):
                    for j in range(COLS):
                        if grid[i][j] == Cyan or grid[i][j] == Lime:
                            grid[i][j] = Springgreen

                parent = list(
                    list((-1, -1) for _ in range(COLS)) for _ in range(ROWS))
                fila = queue()
                for j in range(COLS):
                    fila.insert((0, j))
                    parent[0][j] = 0, j
                color = Springgreen

                i, j = 0, 0

                while fila.not_empty():
                    i, j = fila.pop()
                    if i == ROWS - 1: break
                    if ((i + 1 < ROWS) and grid[i + 1][j] == color
                            and parent[i + 1][j] == (-1, -1)):
                        parent[i + 1][j] = (i, j)
                        paint_position(screen, i + 1, j, color, show=True)
                        fila.insert((i + 1, j))
                    pygame.draw.rect(screen ,  Lime  , ( 50 + 5*x , 50 + 5*y , 5 , 5 ) )
                    pygame.display.update()

                    current = (x,y)

                if current == source:
                    pygame.draw.rect(screen ,  Green  , ( 50 + 5*x , 50 + 5*y , 5 , 5 ) )
                    pygame.display.update()
                    running = False
                    continue
            else:
                running = False


if __name__ == "__main__":
    Q1 = queue()
    Q2 = queue()
    S1 = stack()
    S2 = stack() 

    NO = Thread(target=runner, args = ( 0, Blue,    (1,1)    ,     Q1        , 0.01 )   )
    NE = Thread(target=runner, args = ( 1, Cyan,(COLS-1,1)       ,    Q2     , 0.01 )   )
    SE = Thread(target=runner, args = ( 2, Dark_red,(1,ROWS-1)    ,     S1   , 0.01 )   )
    SO = Thread(target=runner, args = ( 3, Dark_yellow,(COLS-1,ROWS-1),   S2 , 0.01 )   )

    NO.start()
    NE.start()
    SE.start()
    SO.start()

    NO.join()
예제 #11
0
def bfs(graph, node_position, source = 0,steps_mode = False):
    
    from algorithms.data_struct.queue import queue
    import pygame,time
    from algorithms.colors import Springgreen,Cyan,Red,Green,Yellow,Lime,Black,White,deepskyblue
    process_list = queue()
    seen = list(False for x in range(len(graph)))                                   # haven't seen anyone yet

    screen_height = 700
    screen_width = 1300
    screen = pygame.display.set_mode((screen_width,screen_height))

    screen.fill((0,0,0))

    pygame.init()


    Black	     =	    (0,0,0)
    White	     =	    (255,255,255)
    Red  	     =	    (255,0,0)
    Lime	     =	    (0,255,0)
    Blue	     =	    (0,0,200)
    Yellow	     =	    (255,255,0)
    Dark_yellow  =      (250,200,0)
    Cyan 	     =	    (0,255,255)
    Green  	     =	    (0,180,0)
    Springgreen	 =      (0,255,127)

    source_color = Green
    node_color = Blue
    current_color = Lime
    source_radius = 5    
    node_radius = 5


    font = pygame.font.Font('freesansbold.ttf',30)
    text = font.render("BFS",True,(0,255,0))                   # informative node       
    screen.blit(text,text.get_rect(center = (1150,50)))
    
    font = pygame.font.Font('freesansbold.ttf',25)
    
    pygame.draw.circle(screen,(0,255,255), (1000,185),10)
    text = font.render("memory queue",True,(0,255,255))
    screen.blit(text,text.get_rect(center = (1110,183)))                             # informative node   
    text = font.render("(fila de processamento)",True,(0,255,255))
    screen.blit(text,text.get_rect(center = (1100,220)))

    pygame.draw.circle(screen,  Lime,(1000,250)  ,10 )
    pygame.draw.circle(screen,  Springgreen, (1000,250)  ,7 )
    text = font.render("seen",True,Springgreen,20)
    screen.blit(text,text.get_rect(center = (1060,250)))
    pygame.display.update()
    

    for node in range(len(graph)):
        for neighbour in graph[node]:
            node1 = node_position[node]
            node2 = node_position[neighbour]
            pygame.draw.line(screen,(255,255,255), node1, node2,2)
            
    
    #draw circles (nodes)
    for node_number in range(len(graph)):                                                          # draw nodes
        if node_number == source:
            pygame.draw.circle(screen,source_color,node_position[node_number],source_radius)

        else:
            pygame.draw.circle(screen, node_color, node_position[node_number], node_radius)
    
    pygame.display.update()




    n_layer = 0   # number of nodes in cur layer
    missing = 1   # missing nodes in current node

    pause = True
    current = source
    process_list.insert(source)
    while True :
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()                   #exit pygame,
                quit()                          #exit() program


            
            if event.type == pygame.KEYDOWN:        
                if event.key == pygame.K_SPACE:     #press breakspace to pause or play
                    pause = not pause   
                    time.sleep(0.2)
        
        if pause:
            continue
        
        if steps_mode: #pause every step of the algorithm
            pause = True  #when this iteration ends,the animation is paused

        if process_list.not_empty(): 
            
            if missing == 0:
                time.sleep(1)    
                missing = n_layer
                n_layer = 0

                
            

            pygame.draw.circle(screen,  Lime, node_position[current] ,8 )
            pygame.draw.circle(screen,  Springgreen, node_position[current] ,6 )

            missing -= 1
            current = process_list.pop()
            seen[current] = True
            
            #pygame.draw.circle(screen, Lime , node_position[current] , 6)

            for neighbour in graph[current]:
                if seen[neighbour]:
                    continue
                else:
                    n_layer += 1
                    pygame.draw.circle(screen,  Cyan, node_position[neighbour] , 8)
                    process_list.insert(neighbour)



        pygame.display.update()
def cycleWith1NodeShortest(graph,
                           node_position,
                           source=0,
                           Time=0.15,
                           cycle_color=(255, 255, 255)):
    from algorithms.colors import Dark_red, Flame, Cyan, White, Blue, Red, Black, Springgreen, Green, Lime, Cream, Dark_yellow, Yellow, lightsteelblue, Teal
    from algorithms.data_struct.queue import queue

    pygame.init()

    screen_height = 700
    screen_width = 1300
    screen = pygame.display.set_mode((screen_width, screen_height))

    screen.fill((200, 200, 200))

    N = len(graph)  #number of nodes in the graph
    display_graph(screen, graph, node_position, source)

    color = list(Blue for _ in range(N))
    color[source] = White

    parent = list(-1 for _ in range(N))

    Q = queue()

    color_list = [Springgreen, Dark_yellow, Teal, Red]
    i = 0

    for node in graph[source]:
        color[node] = color_list[i]
        i += 1

        parent[node] = source
        mark(screen, node_position[node], color[node])
        Q.insert(node)

    pause = False
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:  #press breakspace to pause or play
                    pause = not pause
                    time.sleep(0.2)

        if pause:
            continue

        if Q.not_empty():
            cur = Q.pop()

            mark(screen, node_position[cur], color[cur], Time=Time)

            for neighbour in graph[cur]:

                if color[neighbour] == Blue:

                    color[neighbour] = color[cur]
                    parent[neighbour] = cur
                    Q.insert(neighbour)
                    mark(screen, node_position[neighbour], Cyan, Time=Time)

                elif neighbour != source and color[neighbour] != color[cur]:

                    font = pygame.font.Font('freesansbold.ttf', 30)
                    text = font.render("Found!", True, cycle_color)
                    screen.blit(text, text.get_rect(center=(930, 400)))
                    mark(screen, node_position[neighbour], cycle_color)

                    time.sleep(2)
                    arrow(screen, node_position[neighbour], node_position[cur],
                          cycle_color, Black)
                    show_cycle(screen,
                               parent,
                               node_position,
                               neighbour,
                               cur,
                               source,
                               cycle_color=cycle_color)
                    Q = queue()  #empty queue
                    pause = True
                    break