Advertisement
courtneythurston

Untitled

Mar 8th, 2021
728
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.68 KB | None | 0 0
  1. class Solution {
  2.     public int numIslandsForReal(char[][] grid, int row, int col, int numberOfRows, int numberOfCols, int isIsland) {
  3.         if (isValid(grid, row, col, numberOfCols, numberOfRows) && ((grid[row][col] == '0') || (grid[row][col] == '9'))){
  4.             return 0;
  5.         }
  6.         if (isValid(grid, row, col, numberOfCols, numberOfRows)){
  7.             if (grid[row][col] == '1'){
  8.                 grid[row][col] = '9';
  9.                 isIsland = numIslandsForReal(grid, row+1, col+0, numberOfRows, numberOfCols, isIsland);
  10.                 isIsland = numIslandsForReal(grid, row+0, col+1, numberOfRows, numberOfCols, isIsland);
  11.                 isIsland = numIslandsForReal(grid, row-1, col-0, numberOfRows, numberOfCols, isIsland);
  12.                 isIsland = numIslandsForReal(grid, row-0, col-1, numberOfRows, numberOfCols, isIsland);
  13.             }
  14.         }
  15.         isIsland = 1;
  16.         return isIsland;
  17.     }
  18.    
  19.     public boolean isValid(char[][] grid, int row, int col, int numberOfCols, int numberOfRows){
  20.         if ((row < numberOfRows) && (col < numberOfCols) && (row >= 0) && (col >= 0)){
  21.             return true;
  22.         }
  23.         else{
  24.             return false;
  25.         }
  26.     }
  27.    
  28.     public int numIslands(char[][] grid)
  29.     {
  30.         int row = 0;
  31.         int col = 0;
  32.         int numberOfRows = grid.length;
  33.         int numberOfCols = grid[0].length;
  34.         int count = 0;
  35.         int isIsland = 0;
  36.         for (int i=0; i<numberOfRows; i++){
  37.             for (int j=0; j<numberOfCols; j++){
  38.                 count += numIslandsForReal(grid, row, col, numberOfRows, numberOfCols, isIsland);
  39.             }
  40.         }
  41.         return count;
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement