diff --git a/src/Search.java b/src/Search.java index cebb278..20eea74 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,56 @@ 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 = new LinkedList<>(); + queue.add(start); + while(!queue.isEmpty()) { + int[] curr = queue.poll(); + int currROW = curr[0]; + int currCOL = curr[1]; + if (visited[currROW][currCOL]) continue; + visited[currROW][currCOL] = true; + if (maze[currROW][currCOL]=='c') return curr; + queue.addAll(getNeighbors(maze, curr)); + } + throw new HungryRatException(); + } + public static List getNeighbors(char[][] maze, int[] curr) { + int currROW = curr[0]; + int currCOL = curr[1]; + //UP [-1, 0] + //DOWN [ 1, 0] + //LEFT [ 0,-1] + //RIGHT [ 0, 1] + int[][] directions = { + {-1,0},{1,0},{0,-1},{0,1} + }; + List moves = new ArrayList<>(); + for (int[] dir : directions) { + int newROW = currROW + dir[0]; + int newCOL = currCOL + dir[1]; + if (newROW>=0&& + newROW=0&& + newCOL