Created
          January 22, 2020 16:54 
        
      - 
      
 - 
        
Save phellipealexandre/081b7ad86b41f63d48140978e6048163 to your computer and use it in GitHub Desktop.  
  
    
      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
    
  
  
    
  | public class IslandMatrixCalculator { | |
| public int calculateNumberOfIslands(int[][] matrix) { | |
| int islands = 0; | |
| if (matrix.length == 0) return islands; | |
| for (int i=0; i<matrix.length; i++) { | |
| for (int j=0; j<matrix[0].length; j++) { | |
| if (matrix[i][j] == 1) { | |
| removeIsland(matrix, i, j); | |
| islands++; | |
| } | |
| } | |
| } | |
| return islands; | |
| } | |
| private void removeIsland(int[][] matrix, int i, int j) { | |
| if (matrix[i][j] == 1) { | |
| matrix[i][j] = 0; | |
| removeIsland(matrix, i, Math.max(0, j-1)); // [i, j-1] | |
| removeIsland(matrix, Math.max(0, i-1), j); // [i-1, j] | |
| removeIsland(matrix, i, Math.min(matrix[0].length-1, j+1)); // [i, j+1] | |
| removeIsland(matrix, Math.min(matrix.length-1, i+1), j); // [i+1, j] | |
| } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment