Skip to content
Open
Show file tree
Hide file tree
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
53 changes: 52 additions & 1 deletion src/Fire.java
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import java.util.LinkedList;
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 +41,54 @@ 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;



int rows = forest.length;
int cols = forest[0].length;

boolean[][] visited = new boolean[rows][cols];

// Check that starting point is a tree
if (forest[matchR][matchC] != 't') {
return -1;
}

int[][] directions = {
{-1, 0}, // up
{1, 0}, // down
{0, -1}, // left
{0, 1} // right
};

Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{matchR, matchC, 0});
visited[matchR][matchC] = true;

int maxTime = 0;

while (!queue.isEmpty()) {
int[] current = queue.poll();
int r = current[0];
int c = current[1];
int time = current[2];

maxTime = Math.max(maxTime, time);

for (int[] dir : directions) {
int newR = r + dir[0];
int newC = c + dir[1];

if (newR >= 0 && newR < rows && newC >= 0 && newC < cols
&& !visited[newR][newC]
&& forest[newR][newC] == 't') {

visited[newR][newC] = true;
queue.add(new int[]{newR, newC, time + 1});
}
}
}

return maxTime;
}
}
54 changes: 54 additions & 0 deletions src/FireTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,58 @@ public void testTimeToBurnExample() {

assertEquals(expected, actual);
}

@Test
public void testSingleTree() {
char[][] forest = {
{'t'}
};
assertEquals(0, Fire.timeToBurn(forest, 0, 0));
}

@Test
public void testSingleEmptySpace() {
char[][] forest = {
{'.'}
};
assertEquals(-1, Fire.timeToBurn(forest, 0, 0));
}

@Test
public void testDisconnectedTrees() {
char[][] forest = {
{'t', '.', 't'},
{'.', '.', '.'},
{'t', '.', 't'}
};
assertEquals(0, Fire.timeToBurn(forest, 0, 0));
}

@Test
public void testFullBlockOfTrees() {
char[][] forest = {
{'t', 't'},
{'t', 't'}
};
assertEquals(2, Fire.timeToBurn(forest, 0, 0));
}

@Test
public void testFireStartsOnGround() {
char[][] forest = {
{'t', 't'},
{'.', 't'}
};
assertEquals(-1, Fire.timeToBurn(forest, 1, 0));
}

@Test
public void testEdgeSpread() {
char[][] forest = {
{'t', 't', 't', '.', '.'},
{'.', '.', 't', '.', '.'},
{'.', '.', 't', 't', 't'}
};
assertEquals(6, Fire.timeToBurn(forest, 0, 0));
}
}