

from __future__ import annotations

import time

lowercase_       		=  list[tuple[int, int]]

lowercase_       		=  [
    [0, 0, 0, 0, 0, 0, 0],
    [0, 1, 0, 0, 0, 0, 0],  # 0 are free path whereas 1's are obstacles
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 1, 0, 0, 0, 0],
    [1, 0, 1, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 1, 0, 0],
]

lowercase_       		=  [[-1, 0], [0, -1], [1, 0], [0, 1]]  # up, left, down, right


class  A						:







    """simple docstring"""





    def __init__(      self :       List[Any],lowercase_ :       int,lowercase_ :       int,lowercase_ :       int,lowercase_ :       int,lowercase_ :       Node | None		)->    str:





        '''simple docstring'''







        A__          =   pos_x
        A__          =   pos_y
        A__          =   (pos_y, pos_x)
        A__          =   goal_x
        A__          =   goal_y
        A__          =   parent




class  A						:







    """simple docstring"""





    def __init__(      self :       str,lowercase_ :       tuple[int, int],lowercase_ :       tuple[int, int]		)->    Any:





        '''simple docstring'''







        A__          =   Node(start[1],start[0],goal[1],goal[0],lowercase_		)
        A__          =   Node(goal[1],goal[0],goal[1],goal[0],lowercase_		)

        A__          =   [self.start]
        A__          =   False


    def 						snake_case__     (      self :       Optional[int]		)->    Path | None:





        '''simple docstring'''







        while self.node_queue:
            A__          =   self.node_queue.pop(0		)

            if current_node.pos == self.target.pos:
                A__          =   True
                return self.retrace_path(lowercase_		)

            A__          =   self.get_successors(lowercase_		)

            for node in successors:
                self.node_queue.append(lowercase_		)

        if not self.reached:
            return [self.start.pos]
        return None


    def 						snake_case__     (      self :       Dict,lowercase_ :       Node		)->    list[Node]:





        '''simple docstring'''







        A__          =   []
        for action in delta:
            A__          =   parent.pos_x + action[1]
            A__          =   parent.pos_y + action[0]
            if not (0 <= pos_x <= len(grid[0]		) - 1 and 0 <= pos_y <= len(lowercase_		) - 1):
                continue

            if grid[pos_y][pos_x] != 0:
                continue

            successors.append(
                Node(lowercase_,lowercase_,self.target.pos_y,self.target.pos_x,lowercase_		)		)
        return successors


    def 						snake_case__     (      self :       Tuple,lowercase_ :       Node | None		)->    Path:





        '''simple docstring'''







        A__          =   node
        A__          =   []
        while current_node is not None:
            path.append((current_node.pos_y, current_node.pos_x)		)
            A__          =   current_node.parent
        path.reverse()
        return path




class  A						:







    """simple docstring"""





    def __init__(      self :       Dict,lowercase_ :       List[Any],lowercase_ :       List[str]		)->    Optional[Any]:





        '''simple docstring'''







        A__          =   BreadthFirstSearch(lowercase_,lowercase_		)
        A__          =   BreadthFirstSearch(lowercase_,lowercase_		)
        A__          =   False


    def 						snake_case__     (      self :       List[Any]		)->    Path | None:





        '''simple docstring'''







        while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
            A__          =   self.fwd_bfs.node_queue.pop(0		)
            A__          =   self.bwd_bfs.node_queue.pop(0		)

            if current_bwd_node.pos == current_fwd_node.pos:
                A__          =   True
                return self.retrace_bidirectional_path(
                    lowercase_,lowercase_		)

            A__          =   current_bwd_node
            A__          =   current_fwd_node

            A__          =   {
                self.fwd_bfs: self.fwd_bfs.get_successors(lowercase_		),
                self.bwd_bfs: self.bwd_bfs.get_successors(lowercase_		),
            }

            for bfs in [self.fwd_bfs, self.bwd_bfs]:
                for node in successors[bfs]:
                    bfs.node_queue.append(lowercase_		)

        if not self.reached:
            return [self.fwd_bfs.start.pos]
        return None


    def 						snake_case__     (      self :       List[str],lowercase_ :       Node,lowercase_ :       Node		)->    Path:





        '''simple docstring'''







        A__          =   self.fwd_bfs.retrace_path(lowercase_		)
        A__          =   self.bwd_bfs.retrace_path(lowercase_		)
        bwd_path.pop()
        bwd_path.reverse()
        A__          =   fwd_path + bwd_path
        return path


if __name__ == "__main__":
     # all coordinates are given in format [y,x]
     import doctest

     doctest.testmod()
     lowercase_       		=  (0, 0)
     lowercase_       		=  (len(grid) - 1, len(grid[0]) - 1)
     for elem in grid:
          print(elem)

     lowercase_       		=  time.time()
     lowercase_       		=  BreadthFirstSearch(init, goal)
     lowercase_       		=  bfs.search()
     lowercase_       		=  time.time() - start_bfs_time

     print("Unidirectional BFS computation time : ", bfs_time)

     lowercase_       		=  time.time()
     lowercase_       		=  BidirectionalBreadthFirstSearch(init, goal)
     lowercase_       		=  bd_bfs.search()
     lowercase_       		=  time.time() - start_bd_bfs_time

     print("Bidirectional BFS computation time : ", bd_bfs_time)








from __future__ import annotations



def _a				(	lowerCamelCase:   list[float]					,				lowerCamelCase:   Tuple )	->						List[str]:







      '''simple docstring'''






      print(F"""Vertex\tShortest Distance from vertex {src}""" )
      for i, d in enumerate(lowerCamelCase ):
            print(F"""{i}\t\t{d}""" )



def _a				(	lowerCamelCase:   list[dict[str, int]]					,				lowerCamelCase:   list[float]					,				lowerCamelCase:   int )	->						Union[str, Any]:







      '''simple docstring'''






      for j in range(lowerCamelCase ):
            __A   ,						__A   ,						__A          =				(graph[j][k] for k in ['''src''', '''dst''', '''weight'''])
            if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]:
                  return True
      return False



def _a				(	lowerCamelCase:   list[dict[str, int]]					,				lowerCamelCase:   int					,				lowerCamelCase:   int					,				lowerCamelCase:   int )	->						list[float]:







      '''simple docstring'''






      __A          =				[float('''inf''' )] * vertex_count
      __A          =				0.0

      for _ in range(vertex_count - 1 ):
            for j in range(lowerCamelCase ):
                  __A   ,						__A   ,						__A          =				(graph[j][k] for k in ['''src''', '''dst''', '''weight'''])

                  if distance[u] != float('''inf''' ) and distance[u] + w < distance[v]:
                        __A          =				distance[u] + w

      __A          =				check_negative_cycle(lowerCamelCase					,				lowerCamelCase					,				lowerCamelCase )
      if negative_cycle_exists:
            raise Exception('''Negative cycle found''' )

      return distance


if __name__ == "__main__":
       import doctest

       doctest.testmod()

       snake_case__					:							Dict													=     int(input('Enter number of vertices: ').strip())
       snake_case__					:							Optional[int]													=     int(input('Enter number of edges: ').strip())

       snake_case__					:							list[dict[str, int]]													=     [{} for _ in range(E)]

       for i in range(E):
              print('Edge ', i + 1)
              snake_case__						,    snake_case__						,    snake_case__					:							Dict													=     (
                  int(x)
                  for x in input('Enter source, destination, weight: ').strip().split(' ')
              )
              snake_case__					:							List[Any]													=     {'src': src, 'dst': dest, 'weight': weight}

       snake_case__					:							Union[str, Any]													=     int(input('\nEnter shortest path source:').strip())
       snake_case__					:							List[Any]													=     bellman_ford(graph, V, E, source)
       print_distance(shortest_distance, 0)





