0911.2024.Today I Learned

Sungju Kim·2024년 9월 12일

Sparta_Coding_Camp_TIL

목록 보기
34/53

Question

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.

Example 1:
Input: grid = [
["1","1","1","1","0"],
["1","1","0","1","0"],
["1","1","0","0","0"],
["0","0","0","0","0"]
]
Output: 1

Example 2:
Input: grid = [
["1","1","0","0","0"],
["1","1","0","0","0"],
["0","0","1","0","0"],
["0","0","0","1","1"]
]
Output: 3

Constraints:
m == grid.length
n == grid[i].length
1 <= m, n <= 300
grid[i][j] is '0' or '1'.

My Solution

import java.util.*;

class Solution {
    public int numIslands(char[][] grid) {
        int answer = 0;

        // Check through all the grid
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == '1') {
                    check(grid, j, i); // call check with coordinates
                    answer++;
                }
            }
        }
        return answer;
    }

    public void check(char[][] grid, int x, int y) {
        // base case: out of bounds or already visited or water
        if (y >= grid.length || x >= grid[0].length || x < 0 || y < 0 || grid[y][x] == '0' || grid[y][x] == '2') {
            return;
        }

        grid[y][x] = '2'; // mark visited land

        // north
        check(grid, x, y - 1);
        // south
        check(grid, x, y + 1);
        // east
        check(grid, x + 1, y);
        // west
        check(grid, x - 1, y);
    }
}
profile
Fully ✨committed✨ developer, always eager to learn!

0개의 댓글