From 9a0d64ca21949db506a8d103655206f2aaafdc34 Mon Sep 17 00:00:00 2001 From: tim Date: Tue, 3 Jun 2025 11:48:34 -0700 Subject: [PATCH] saving --- src/Search.java | 117 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 115 insertions(+), 2 deletions(-) diff --git a/src/Search.java b/src/Search.java index cebb278..90f9b65 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. @@ -28,7 +33,115 @@ public class Search { * @throws CrowdedMazeException if there is more than one rat in the maze * @throws HungryRatException if there is no reachable cheese */ - public static int[] nearestCheese(char[][] maze) throws EscapedRatException, CrowdedMazeException, HungryRatException { - return null; + public static int[] nearestCheese(char[][] maze) throws EscapedRatException, CrowdedMazeException, HungryRatException + { + boolean[][] visited = new boolean[maze.length][maze[0].length]; + int[] start = locateRat(maze); + + //Queue + Queue queue = new LinkedList<>(); + + //add + queue.add(start); + + //loop + while(!queue.isEmpty()) + { + int[] current = queue.poll(); + int curR = current[0]; + int curC = current[1]; + + if(visited[curR][curC]) + { + continue; + } + visited[curR][curC] = true; + + if(maze[curR][curC] == 'c') + { + return current; + } + + queue.addAll(getNeighbors(maze, current)); + } + + throw new HungryRatException(); + + /* + empty q + q.add(start) + while q is not empty + current = q.pop + if visited: continue + mark visited + if current is cheese: return current + q.add(neighbors) add all neighbors to q + + 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') + { + int[] validMove = new int[]{newR,newC}; + possibleMoves.add(validMove); + } + } + + return possibleMoves; + } + + public static int[] locateRat(char[][] maze) throws EscapedRatException, CrowdedMazeException + { + int[] location = null; + + //Searching + for(int r = 0; r < maze.length; r++) + { + for(int c = 0; c < maze[r].length; c++) + { + if(maze[r][c] == 'R') + { + if(location != null) + { + throw new CrowdedMazeException(); + } + location = new int[]{r,c}; + } + } + } + + + if(location == null) + { + //Didnt Find + throw new EscapedRatException(); + } + return location; } } \ No newline at end of file