diff --git a/src/Search.java b/src/Search.java index cebb278..827854f 100644 --- a/src/Search.java +++ b/src/Search.java @@ -1,3 +1,8 @@ +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; +import java.util.Queue; + public class Search { /** * Finds the location of the nearest reachable cheese from the rat's position. @@ -29,6 +34,71 @@ public class Search { * @throws HungryRatException if there is no reachable cheese */ public static int[] nearestCheese(char[][] maze) throws EscapedRatException, CrowdedMazeException, HungryRatException { - return null; + int[] start = findRat(maze); + Queue queue = new LinkedList<>(); + queue.add(start); + boolean[][] visited = new boolean[maze.length][maze[0].length]; + + while (!queue.isEmpty()) { + int[] current = queue.poll(); + int curRow = current[0]; + int curCol = current[1]; + + if (maze[curRow][curCol] == 'c') return current; + if (visited[curRow][curCol]) continue; + + visited[curRow][curCol] = true; + + List nextMoves = possibleMoves(maze, current); + queue.addAll(nextMoves); + + } + + throw new HungryRatException(); } + + public static List possibleMoves(char[][] maze, int[] currentLocation) { + int curRow = currentLocation[0]; + int curCol = currentLocation[1]; + + int[][] steps = { + {1, 0}, + {-1, 0}, + {0, 1}, + {0, -1} + }; + + List moves = new ArrayList<>(); + + for (int[] step : steps) { + int newRow = curRow + step[0]; + int newCol = curCol + step[1]; + if (newRow >= 0 && newRow < maze.length && + newCol >= 0 && newCol < maze[0].length && + maze[newRow][newCol] != 'w') { + moves.add(new int[]{newRow, newCol}); + } + } + + return moves; + } + + public static int[] findRat(char[][] maze) throws EscapedRatException, CrowdedMazeException { + int ratCount = 0; + int[] ratLocation = null; + + for (int r = 0; r < maze.length; r++) { + for (int c = 0; c < maze[0].length; c++) { + if(maze[r][c] == 'R') { + ratLocation = new int[]{r, c}; + ratCount++; + } + } + } + + if (ratCount > 1) throw new CrowdedMazeException(); + if (ratCount == 0) throw new EscapedRatException(); + + return ratLocation; + } } \ No newline at end of file