diff --git a/src/Search.java b/src/Search.java index cebb278..6977728 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,77 @@ 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 = ratLocation(maze); + int rows = maze.length; + int cols = maze[0].length; + + boolean[][] visited = new boolean[rows][cols]; + Queue queue = new LinkedList<>(); + queue.add(start); + + while(!queue.isEmpty()) { + int[] current = queue.poll(); + int r = current[0]; + int c = current[1]; + + if(visited[r][c]) continue; + + if(maze[r][c] == 'c') { + return current; + } + + visited[r][c] = true; + + List nextMoves = possibleMoves(maze, current); + queue.addAll(nextMoves); + } + throw new HungryRatException(); + } + + public static List possibleMoves(char[][] maze, int[] currentLoc) { + List moves = new ArrayList<>(); + int[][] directions = { + {-1,0}, + {1, 0}, + {0,-1}, + {0, 1} + }; + + int curR = currentLoc[0]; + int curC = currentLoc[1]; + + for(int[] dir : directions) { + int newR = curR + dir[0]; + int newC = curC + dir[1]; + + if (newR >= 0 && newR < maze.length && + newC >= 0 && newC < maze[0].length && + maze[newR][newC] != 'w') { + moves.add(new int[]{newR, newC}); + } + } + + return moves; + } + + public static int[] ratLocation(char[][] maze) throws CrowdedMazeException, EscapedRatException { + int ratCount = 0; + int[] ratCoords = null; + for(int r = 0; r < maze.length; r++) { + for(int c = 0; c < maze[0].length; c++) { + if(maze[r][c] == 'R') { + ratCoords = new int[]{r,c}; + ratCount++; + } + } + } + + if(ratCount > 1) throw new CrowdedMazeException(); + if(ratCount == 0) throw new EscapedRatException(); + return ratCoords; + } + + public static void main(String[] args) { + } } \ No newline at end of file