Created
May 1, 2015 15:43
-
-
Save richadams8/7d46706b704ffcaf6089 to your computer and use it in GitHub Desktop.
Water Percolation Algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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