Skip to content

3619. 总价值可以被 K 整除的岛屿数目


题目链接

https://leetcode.cn/problems/count-islands-with-total-value-divisible-by-k/

注意事项

数据量很大的时候可能会溢出,使用 long 类型

代码实现

java
class Solution {
    public static int[][] dir = { { 0, 1 }, { 0, -1 }, { 1, 0 }, { -1, 0 } };

    public int countIslands(int[][] grid, int k) {
        // n 行 m 列
        int n = grid.length;
        int m = grid[0].length;

        boolean[][] visited = new boolean[n][m];

        int ans = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (!visited[i][j] && grid[i][j] > 0) {
                    long count = dfs(grid, i, j, visited);
                    if (count % k == 0) {
                        ans++;
                    }
                }
            }
        }
        return ans;
    }

    public long dfs(int[][] grid, int x, int y, boolean[][] visited) {
        long count = grid[x][y];
        visited[x][y] = true;

        for (int i = 0; i < dir.length; i++) {
            int nextX = x + dir[i][0];
            int nextY = y + dir[i][1];

            // 检查越界
            if (nextX < 0 || nextX >= grid.length || nextY < 0 || nextY >= grid[0].length) {
                continue;
            }

            if (!visited[nextX][nextY] && grid[nextX][nextY] > 0) {
                count += dfs(grid, nextX, nextY, visited);
            }
        }
        return count;
    }
}