commit 52ebbfb3359d11a36dbed472d3b9d3749624afe4 Author: mia Date: Thu Oct 16 09:37:38 2025 +0200 Initial commit diff --git a/Path_Finding_L1.py b/Path_Finding_L1.py new file mode 100644 index 0000000..50a5bfb --- /dev/null +++ b/Path_Finding_L1.py @@ -0,0 +1,118 @@ +def initialize_queue_and_visited(start): + """ + Initialisiert die Warteschlange (queue) mit dem Startpunkt und das Set der besuchten Knoten (visited). + + Args: + start (tuple): Startkoordinate im Format (x, y) + + Returns: + tuple: Ein Tupel bestehend aus der Warteschlange (queue) und dem Set der besuchten Knoten (visited). + """ + # raise NotImplementedError("initialize_queue_and_visited() is not implemented yet.") + queue = [(start[0], start[1], [])] + visited = {start} + return (queue,visited) + + +def get_neighbors(x, y, maze, visited): + """ + Berechnet die gültigen Nachbarn (Nachbarzellen) für einen gegebenen Punkt im Labyrinth. + + Args: + x (int): Die X-Koordinate des aktuellen Punktes. + y (int): Die Y-Koordinate des aktuellen Punktes. + maze (list of list of int): Die 2D-Matrix, die das Labyrinth darstellt. + visited (set): Das Set der besuchten Knoten. + + Returns: + list: Eine Liste der Nachbarknoten, die besucht werden können. + """ + + returnval = [] + + for i in (-1, 1): + if y+i < 0 or y+i > (len(maze[0])-1): + continue + position = maze[y+i][x] + # print(f"\nChecking: ({x},{y+i})") + if not position and (y,x+i) not in visited: + print(position) + returnval.append((x, y+i)) + print(returnval) + else: + pass + for i in (-1,1): + if x+i < 0 or x+i > len(maze[0]): + continue + position = maze[y][x+i] + # print(f"\nChecking: ({x+i},{y})") + if not position and (x+i,y) not in visited: + print(position) + returnval.append((x+i, y)) + print(returnval) + else: + pass + + print(returnval) + return returnval + + + + + +def bfs_maze_solver(maze, start, goal): + """ + Führt den Breadth-First Search (BFS) durch, um den kürzesten Pfad im Labyrinth zu finden. + + Args: + maze (list of list of int): Die 2D-Matrix, die das Labyrinth darstellt. + start (tuple): Startkoordinate im Format (x, y) + goal (tuple): Zielkoordinate im Format (x, y) + + Returns: + list or None: Der kürzeste Pfad als Liste von Koordinaten oder None, wenn kein Pfad gefunden wird. + """ + + + + # Initialisiere die Warteschlange und die besuchten Knoten + queue, visited = initialize_queue_and_visited(start) + print(queue) + + while queue: + x,y,path = queue.pop(0) + + if (x,y) == goal: + return path+[(x,y)] + else: + n = get_neighbors(x,y,maze,visited) + for new_x,new_y in n: + visited.add((new_x, new_y)) + queue.append((new_x,new_y,path+[(x,y)])) + + return None + + + # Füge hier den Code für BFS hinzu. + +# Beispiel-Labyrinth +maze = [ + [0, 1, 0, 0, 0], + [0, 1, 0, 1, 0], + [0, 0, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0] +] + +start = (0, 0) +goal = (4, 4) + +# Finde den kürzesten Pfad mit BFS +path = bfs_maze_solver(maze, start, goal) + +# Gib das Ergebnis aus +if path: + print("Path found:", path) + exit() +else: + print("No path found from start to goal.") diff --git a/Path_Finding_L2.py b/Path_Finding_L2.py new file mode 100644 index 0000000..9e89369 --- /dev/null +++ b/Path_Finding_L2.py @@ -0,0 +1,146 @@ +import sys + +class Node(): + def __init__(self, state, parent, action): + self.state = state + self.parent = parent + self.action = action + +class StackFrontier(): + def __init__(self): + self.frontier = [] + + def add(self, node): + self.frontier.append(node) + + def contains_state(self, state): + return any(node.state == state for node in self.frontier) + + def empty(self): + return len(self.frontier) == 0 + + def remove(self): + if self.empty(): + raise Exception("empty frontier") + else: + node = self.frontier[-1] + self.frontier = self.frontier[:-1] + return node + +class QueueFrontier(StackFrontier): + + def remove(self): + if self.empty(): + raise Exception("empty frontier") + else: + node = self.frontier[0] + self.frontier = self.frontier[1:] + return node + +class Maze(): + + def __init__(self, filename): + + # Read file and set height and width of maze + with open(filename) as f: + contents = f.read() + + # Validate start and goal + if contents.count("A") != 1: + raise Exception("maze must have exactly one start point") + if contents.count("B") != 1: + raise Exception("maze must have exactly one goal") + + # Determine height and width of maze + contents = contents.splitlines() + self.height = len(contents) + self.width = max(len(line) for line in contents) + + # Keep track of walls + self.walls = [] + for i in range(self.height): + row = [] + for j in range(self.width): + try: + if contents[i][j] == "A": + self.start = (i, j) + row.append(False) + elif contents[i][j] == "B": + self.goal = (i, j) + row.append(False) + elif contents[i][j] == " ": + row.append(False) + else: + row.append(True) + except IndexError: + row.append(False) + self.walls.append(row) + + self.solution = None + + + def print(self): + """ + Prints the maze to the console, displaying walls, the start and goal positions, + and the solution path if it exists. + + The method uses different characters to represent various elements in the maze: + - '█' for walls + - 'A' for the start position + - 'B' for the goal position + - '*' for the solution path, if available + - ' ' for open spaces + + If a solution has been found, the path from the start to the goal will be shown + with asterisks ('*'). + + Returns: + None + """ + raise NotImplementedError("neighbors method is not implemented yet") + + + def neighbors(self, state): + """ + Returns a list of neighboring states in the maze that can be reached + from the current state. + + Args: + state (tuple): The current position in the maze as (row, col). + + Returns: + list: A list of tuples representing neighboring positions + that can be moved to. + """ + raise NotImplementedError("neighbors method is not implemented yet") + + + def solve(self): + """ + Finds a solution to the maze using breadth-first search (BFS) if one exists. + + Returns: + None: Modifies the class attributes to store the solution path + and number of states explored. + """ + + raise NotImplementedError("solve method is not implemented yet") + + + def output_image(self, filename, show_solution=True, show_explored=False): + raise NotImplementedError("output_image method is not implemented yet") + + +if len(sys.argv) != 2: + sys.exit("Usage: python Path_Finding_L2.py maze.txt") + +m = Maze(sys.argv[1]) +print("Maze:") +m.print() +print("Solving...") +m.solve() +print("States Explored:", m.num_explored) +print("Solution:") +m.print() +#m.output_image("maze.png", show_explored=True) + diff --git a/Programmieraufgabe_BFS_DFS.odt b/Programmieraufgabe_BFS_DFS.odt new file mode 100644 index 0000000..d185c06 Binary files /dev/null and b/Programmieraufgabe_BFS_DFS.odt differ diff --git a/__pycache__/Path_Finding_L1.cpython-312.pyc b/__pycache__/Path_Finding_L1.cpython-312.pyc new file mode 100644 index 0000000..4604b9b Binary files /dev/null and b/__pycache__/Path_Finding_L1.cpython-312.pyc differ diff --git a/maze1.txt b/maze1.txt new file mode 100644 index 0000000..919d53f --- /dev/null +++ b/maze1.txt @@ -0,0 +1,6 @@ +#####B# +##### # +#### # +#### ## + ## +A###### diff --git a/maze2.txt b/maze2.txt new file mode 100644 index 0000000..1e4be0a --- /dev/null +++ b/maze2.txt @@ -0,0 +1,16 @@ +### ######### +# ################### # # +# #### # # # # +# ################### # # # # +# B # # # # +##################### # # # # +# ## # # # # +# # ## ### ## ######### # # # +# # # ## # # # # +# # ## ################ # # # +### ## #### # # # +### ############## ## # # # # +### ## # # # # +###### ######## ####### # # # +###### #### # # +A ###################### diff --git a/test.py b/test.py new file mode 100644 index 0000000..e69e557 --- /dev/null +++ b/test.py @@ -0,0 +1,23 @@ +import Path_Finding_L1 as pf + +start = (0,0) +goal = (4,4) + +maze = [ + [0, 1, 0, 0, 0], + [0, 1, 0, 1, 0], + [0, 0, 0, 1, 0], + [0, 1, 1, 1, 0], + [0, 0, 0, 0, 0] +] + +queue, visited = pf.initialize_queue_and_visited(start) + +neighbors = pf.get_neighbors(start[0],start[1],maze, {(0,2)}) + +pf.bfs_maze_solver(maze, start, goal) + + + +# visited = visited | set(neighbors) +# print(visited)