From ceeecbd4d88b78125b54719a7f28a64d8a6bd28a Mon Sep 17 00:00:00 2001 From: dangrabo <193651636+dangrabo@users.noreply.github.com> Date: Tue, 3 Jun 2025 11:45:53 -0700 Subject: [PATCH] finished livecode --- src/Search.java | 79 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 78 insertions(+), 1 deletion(-) diff --git a/src/Search.java b/src/Search.java index cebb278..56ec408 100644 --- a/src/Search.java +++ b/src/Search.java @@ -1,3 +1,5 @@ +import java.util.*; + public class Search { /** * Finds the location of the nearest reachable cheese from the rat's position. @@ -29,6 +31,81 @@ public class Search { * @throws HungryRatException if there is no reachable cheese */ public static int[] nearestCheese(char[][] maze) throws EscapedRatException, CrowdedMazeException, HungryRatException { - return null; + boolean[][] visited = new boolean[maze.length][maze[0].length]; + int[] start = ratLocation(maze); + + // queue = []; + Queue q = new LinkedList<>(); + // queue.offer(start); + q.offer(start); + + // while queue not empty + while (!q.isEmpty()) { + // current = queue.pop + int[] current = q.poll(); + int curR = current[0]; + int curC = current[1]; + + // if visited: continue + if (visited[curR][curC]) continue; + // mark visited + visited[curR][curC] = true; + + // if current is cheese: return current + if (maze[curR][curC] == 'c') return current; + + // add all neighbors to queue + // for (int[] neighbor : getNeighbors(maze, current)) q.offer(neighbor); + q.addAll(getNeighbors(maze, current)); + } + + // throw HungryRatException + throw new HungryRatException(); + } + + public static List getNeighbors(char[][] maze, int[] current) { + int curR = current[0]; + int curC = current[1]; + + int[][] directions = { + {-1, 0}, // UP + {1, 0}, // DOWN + {0, -1}, // LEFT + {0, 1} // RIGHT + }; + + List possibleMoves = new ArrayList<>(); + + for (int[] direction : directions) { + int changeR = direction[0]; + int changeC = direction[1]; + + int newR = curR + changeR; + int newC = curC + changeC; + + if (newR >= 0 && newR < maze.length && + newC >= 0 && newC < maze[newR].length && + maze[newR][newC] != 'w') { + possibleMoves.add(new int[] {newR, newC}); + } + } + + return possibleMoves; + } + + public static int[] ratLocation(char[][] maze) throws EscapedRatException, CrowdedMazeException { + int[] location = null; + + for (int r = 0; r < maze.length; r++) { + for (int c = 0; r < maze[r].length; c++) { + if (maze[r][c] == 'R') { + if (location != null) throw new CrowdedMazeException(); + location = new int[] {r, c}; + } + } + } + + if (location == null) throw new EscapedRatException(); + return location; } } \ No newline at end of file