joshita / dev

Published

- 2 min read

Number of Islands

img of Number of Islands

Number of Islands

Given an m x n 2D binary grid grid which represents a map of ‘1’s (land) and ‘0’s (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water.

TotalValue

   private void noOfIsland(int [][] grid) {

        int row = grid.length;
        int col = grid[0].length;
        int noOfIsland = 0;
        for (int i=0; i < row; i++) {
            for (int j =0; j < col; j++) {
                if(grid[i][j] == 1) {
                    noOfIsland = noOfIsland + 1;
                    bfs(grid, row, col, grid);
                }
            }
        }
    }

    private void bfs(int [][] grid, int row, int col, int [][] directions) {
        Queue<int[]> queue = new LinkedList<>();
        queue.add(new int[grid[row][col]]); 
        
        while (queue.isEmpty()) {
            List<int[]> neighbours = getNeighbours(directions, row, col, grid);
            for(int [] neighbour : neighbours) {
                queue.add(new int [] {neighbour[0], neighbour[1]});
                grid[neighbour[0]][neighbour[1]] = 1;
            }
        }
    }

    private List<int[]> getNeighbours(int [][] directions, int row, int col, int[][] grid) {
        List<int[]> list = new ArrayList<>();

        for (int [] direction : directions) {
            int newRow = row + direction[0];
            int newCol = col + direction[1];
            if(newRow < 0 || newCol > grid[grid.length][grid[0].length] || grid[newRow][newCol] != 1) {
                continue;
            }
            list.add(new int[]{newRow, newCol});
        }
        return list;
    }