4ms Java solution [easy to understand]


  • 3
    A
    public class Solution {
        
        public int numIslands(char[][] grid) {
            int c = 0;
            for(int i = 0; i < grid.length; i++)
    			for(int j = 0; j < grid[0].length; j++) 
    				if(grid[i][j] == '1') {
    					check(grid, i, j);
    					c++;
    				}
    				
    		return c;
        }
    
        public void check(char[][] array, int i, int j) {
        		if(j >= array[0].length || i >= array.length || j < 0 || i < 0 || array[i][j] == '0' || array[i][j] == '2')
        			return;
        		
        		if(array[i][j] == '1')
        			array[i][j] = '2';
        		
        		// check right
        		check(array, i, j+1);
        		
        		// check down
        		check(array, i+1, j);
        		
        		// check left
        		check(array, i, j-1);
        		
        		// check up
        		check(array, i-1, j);
    
    	}
    }
    

  • 0
    S

    @Ali-X Nice solution, I have rewrite the code to be more clear and cocise

        public char getTile(int x, int y, char[][] grid) {
            if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length) return 0;
            return grid[x][y];
        }
    
        public int numIslands(char[][] grid) {
            if (grid.length == 0) return 0;
            int island = 0;
            for (int i = 0; i < grid.length; i++) {
                for (int j = 0; j < grid[i].length; j++) {
                    if (checkAndPaint(grid, i, j)) island++;
                }
            }
            return island;
        }
    
        public boolean checkAndPaint(char[][] grid, int x, int y) {
            int type = getTile(x, y, grid);
            if (type != '1') return false;
            grid[x][y] = '2';
            checkAndPaint(grid, x - 1, y);
            checkAndPaint(grid, x, y - 1);
            checkAndPaint(grid, x + 1, y);
            checkAndPaint(grid, x, y + 1);
            return true;
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.