Commit 70660ecf authored by Matthew Waters's avatar Matthew Waters
Browse files

Hello

parent 40511497
......@@ -19,6 +19,7 @@ public class FloodGame {
StringBuilder buf = new StringBuilder();
for (int r = 0; r < grid.edgeSize(); r++) {
for (int c = 0; c < grid.edgeSize(); c++) {
buf.append(grid.getColorAt(r, c));
}
buf.append('\n');
}
......@@ -28,13 +29,74 @@ public class FloodGame {
// TODO
static boolean gameOver(FloodGrid grid) {
return false; // placeholder
int targetColor = grid.getColorAt(0);
for(int i = 1; i< grid.numCells(); i++) {
if(grid.getColorAt(i) != targetColor) {
return false;
}
}
return true;
}
// TODO
static void flood(FloodGrid grid, int newColor) {
boolean[][] visited = new boolean[grid.edgeSize()][grid.edgeSize()];
int prevColor = grid.getColorAt(0,0);
flood(grid, visited, 0, 0, prevColor, newColor);
}
/* The first helper for the flood algorithm floods FROM a particular row and
* column, changing any contiguous cells of prevColor into newColor. It
* must consider all four directions, but only proceed if okayToVisit.
*/
private static void flood(
FloodGrid grid,
boolean[][] visited,
int row,
int column,
int prevColor,
int newColor)
{
visited[row][column] = true;
grid.setColorAt(row, column, newColor);
// Down
if(okayToVisit(grid, visited, row+1, column, prevColor)) {
flood(grid, visited, row+1, column, prevColor, newColor);
}
// Right
if(okayToVisit(grid, visited, row, column+1, prevColor)) {
flood(grid, visited, row, column+1, prevColor, newColor);
}
// Up
if(okayToVisit(grid, visited, row-1, column, prevColor)) {
flood(grid, visited, row-1, column, prevColor, newColor);
}
// Left
if(okayToVisit(grid, visited, row, column-1, prevColor)) {
flood(grid, visited, row, column-1, prevColor, newColor);
}
}
/* The last helper for the flood algorithm just determines if it's okay to
* visit a particular coordinate -- it's in-bounds, hasn't been visited yet,
* and matches the existing color.
*/
private static boolean okayToVisit(
FloodGrid grid,
boolean[][] visited,
int row,
int column,
int color)
{
return (row >= 0
&& row < grid.edgeSize()
&& column >= 0
&& column < grid.edgeSize()
&& !visited[row][column]
&& grid.getColorAt(row, column) == color);
}
public static void main(String[] args) throws IOException {
final int numColors = 4;
FloodGrid grid = new FloodGridArray2D(6);
......
......@@ -34,7 +34,7 @@ class FloodGridArray2D implements FloodGrid {
grid[row][column] = color;
}
// TODO
public void setColorAt(int index, int color) {
setColorAt(index/edgeSize(), index%edgeSize(), color);
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment