Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 87 additions & 1 deletion src/Search.java
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -29,6 +34,87 @@ 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<int[]> queue = new LinkedList<>();
queue.add(start);

while(!queue.isEmpty()) {
int[] current = queue.poll();
int currR = current[0];
int currC = current[1];

if(visited[currR][currC]) {
continue;
}

visited[currR][currC] = true;
if(maze[currR][currC] == 'c') {
return current;
}

// for(int[] neighbor : getNeighbors(maze, current)) {
// queue.add(neighbor);
// }
queue.addAll(getNeighbors(maze, current));
}

throw new HungryRatException();
}

public static List<int[]> getNeighbors(char[][] maze, int[] current) {
int currR = current[0];
int currC = current[1];

int[][] directions = {
{-1, 0},
{1, 0},
{0, -1},
{0, 1}
};
// Up [-1, 0]
// Down [1, 0]
// Left [0, -1]
// Right [0, 1]

List<int[]> possibleMoves = new ArrayList<>();

for(int[] direction : directions) {
int changeR = direction[0];
int changeC = direction[1];

int newR = currR + changeR;
int newC = currC + changeC;

if(newR >= 0 && newR < maze.length &&
newC >= 0 && newC < maze[newR].length &&
maze[newR][newC] != 'w') {
int[] validMove = {newR, newC};
possibleMoves.add(validMove);
}
}

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; c < 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;
}
}