Skip to content

Instantly share code, notes, and snippets.

@richadams8
Created May 1, 2015 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richadams8/7d46706b704ffcaf6089 to your computer and use it in GitHub Desktop.
Save richadams8/7d46706b704ffcaf6089 to your computer and use it in GitHub Desktop.
Water Percolation Algorithm
package com.radams.play;
import org.junit.Test;
/**
* @author Rich Adams
*/
public class WaterPercolation
{
public boolean percolate(int[][] grid)
{
int[][] tempGrid = grid.clone();
for (int topIndex = 0; topIndex < grid[0].length; topIndex++)
{
if (checkCell(tempGrid, 0, topIndex))
{
return true;
}
}
return false;
}
protected boolean checkCell(int[][] grid, int row, int col)
{
boolean works;
if(grid[row][col] == 0)
{
works = false;
}
else if(row == (grid.length - 1) && grid[row][col] == 1)
{
works = true;
}
else
{
grid[row][col] = 0;
int left = col - 1;
int right = col + 1;
int below = row + 1;
works = (below < grid.length && checkCell(grid, below, col)) ||
(left > 0 && checkCell(grid, row, left)) ||
(right < grid[row].length && checkCell(grid, row, right));
}
return works;
}
@Test
public void testPercolate()
{
int[][] testGrid = {{1, 0, 1, 1},
{1, 1, 0, 1},
{0, 0, 0, 0}};
assert(percolate(testGrid));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment