Advertisement
courtneythurston

Untitled

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