Time Cost

13min30s

Code

class Solution {
public:
    int numIslands(vector<vector<char>>& grid) {
        if (grid.empty()) return 0;

        int m = grid.size(), n = grid[0].size(), islands = 0;
        vector<int> directions = {0, 1, 0, -1, 0}; // Right, Down, Left, Up

        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == '1') {
                    islands++;
                    queue<pair<int, int>> q;
                    q.push({i, j});
                    grid[i][j] = '0'; // Mark as visited

                    while (!q.empty()) {
                        auto [x, y] = q.front();
                        q.pop();

                        // Explore all 4 directions
                        for (int d = 0; d < 4; d++) {
                            int newX = x + directions[d];
                            int newY = y + directions[d + 1];

                            if (newX >= 0 && newX < m && newY >= 0 && newY < n && grid[newX][newY] == '1') {
                                grid[newX][newY] = '0'; // Mark as visited
                                q.push({newX, newY});
                            }
                        }
                    }
                }
            }
        }
        return islands;
    }

};