Advertisement
courtneythurston

Untitled

Mar 7th, 2021
835
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.33 KB | None | 0 0
  1. class Solution {
  2.    
  3.     public int numIslands(char[][] grid) {
  4.         int[] rowMovement = {-1, 0, 1, 0};
  5.         int[] colMovement = {0, -1, 0, 1};
  6.         int numberOfRows = grid.length;
  7.         int numberOfCols = grid[0].length;
  8.         int row;
  9.         int col;
  10.         int movingRow = 0;
  11.         int movingCol = 0;
  12.         int tempRow = 0;
  13.         int tempCol = 0;
  14.         int count = 0;
  15.         char c;
  16.         Queue<Integer> q = new ArrayDeque<Integer>();
  17.        
  18.         for (row = 0; row < numberOfRows; row++){
  19.             for (col = 0; col < numberOfCols; col++){
  20.                 if (grid[row][col] == '1'){ //if it encounters a 1, increment count. Below changes
  21.                     q.add(row);
  22.                     q.add(col);
  23.                     movingRow = row;
  24.                     movingCol = col;
  25.                     while(!q.isEmpty()){
  26.                         movingRow = q.remove();
  27.                         movingCol = q.remove();
  28.                         c = grid[movingRow][movingCol];
  29.                         grid[movingRow][movingCol] = '9';//indicate you've visited now
  30.                         if (c == '1'){
  31.                             for (int k = 0; k < 4; k++){
  32.                                 tempRow = movingRow+rowMovement[k];
  33.                                 tempCol = movingCol+colMovement[k];
  34.                                 if (isValid(tempRow, tempCol, numberOfCols, numberOfRows, grid)){
  35.                                     q.add(tempRow);
  36.                                     q.add(tempCol);
  37.                                 }                            
  38.                             }  
  39.                         }
  40.                     }
  41.                     count++;
  42.                 }
  43.                 if (grid[row][col] == '9'){
  44.                     continue; //move on in for loop if we've already been here;
  45.                 }
  46.                 else{
  47.                     grid[row][col] = '9'; //set to visited as indicated by 9
  48.                 }  
  49.             }      
  50.         }
  51.         return count;
  52.     }
  53.    
  54.     public boolean isValid(int row, int col, int numberOfCols, int numberOfRows, char[][] grid){
  55.         if ((row < numberOfRows) && (col < numberOfCols) && (row >= 0) && (col >= 0)){
  56.             return true;
  57.         }
  58.         else{
  59.             return false;
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement