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
67 changes: 66 additions & 1 deletion src/Fire.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 Fire {
/**
* Returns how long it takes for all vulnerable trees to be set on fire if a
Expand Down Expand Up @@ -38,6 +43,66 @@ public class Fire {
public static int timeToBurn(char[][] forest, int matchR, int matchC) {
// HINT: when adding to your BFS queue, you can include more information than
// just a location. What other information might be useful?
return -1;
if (forest[matchR][matchC] != 't') {
return 0;
}


int[] start = new int[]{matchR, matchC, 0};
boolean[][] burnt = new boolean[forest.length][forest[0].length];

Queue<int[]> queue = new LinkedList<>();
queue.add(start);

int maxTime = 0;

while(!queue.isEmpty()){
int[] current = queue.poll();

int row = current[0];
int col = current[1];
int time = current[2];

// if the current tree is down continue
if (burnt[row][col]){
continue;
}

burnt[row][col] = true;

List<int[]> moves = possibleMoves(forest, row, col);

// add reachable tree to the queue
for (var move : moves){
int[] toAdd = new int[]{move[0],move[1], time + 1};
queue.add(toAdd);
}

if( time > maxTime){
maxTime = time;
}
}
return maxTime;
}

public static List<int[]> possibleMoves(char[][] forest, int row, int col) {
List<int[]> moves = new ArrayList<>();
int[][] directions = {
{-1, 0}, // up
{ 1, 0}, // down
{ 0,-1}, // left
{ 0, 1} // right
};

for (int[] d : directions) {
int nr = row + d[0], nc = col + d[1];
if (nr >= 0 && nr < forest.length &&
nc >= 0 && nc < forest[0].length &&
forest[nr][nc] == 't') {
moves.add(new int[]{nr, nc});
}
}

return moves;
}
}