查看: 1418| 回复: 1
跳转到指定楼层
上一主题 下一主题
收起左侧

[Leetcode] LeetCode 200 Number of Islands使用BFS有test没有通过,能不能帮忙debug一下?

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
以下是我的代码,有test没有通过。有没有大神可以帮忙debug一下?我被困了很久还是没有debug成功...提供帮助的都加米!!!谢谢!!!

class Coordinate {
        int x, y;
        Coordinate(int x, int y) {
                this.x = x;
                this.y = y;
        }
}
class Solution {
    public int numIslands(char[][] grid) {
        if(grid == null || grid.length == 0 || grid[0].length == 0) return 0;
        
        int n = grid.length;
        int m = grid[0].length;
        int islands = 0;
        
        for(int i = 0; i < n; i++) {
                for(int j = 0; j < m; j++) {
                        if(grid[i][j] != 0) {
                                judgeIslands(grid, i, j);
                                islands++;
                        }
                }
        }
        
        return islands;
    }
   
    public void judgeIslands(char[][] grid, int x, int y) {
            // (1, 0): go right; (0, 1): go down; (0, -1): go up; (-1, 0): go left.
            int[] directionX = {1, 0, 0, -1};
            int[] directionY = {0, 1, -1, 0};
           
            Queue<Coordinate> queue = new LinkedList<>();
            queue.offer(new Coordinate(x, y));
            grid[x][y] = 0;
           
            while(!queue.isEmpty()) {
                    Coordinate coor = queue.poll();
                    for(int i = 0; i < 4; i++) {
                            Coordinate adj = new Coordinate(coor.x + directionX[i], coor.y + directionY[i]);
                            if(!inBound(grid, adj)) continue;
                            if(grid[adj.x][adj.y] != 0) {
                                    queue.offer(adj);
                                    grid[adj.x][adj.y] = 0;
                            }
                    }
            }
    }
   
    public boolean inBound(char[][] grid, Coordinate coor) {
            int n = grid.length;
            int m = grid[0].length;
           
            return coor.x >= 0 && coor.x < n && coor.y >= 0 && coor.y < m;
    }
}

上一篇:Leetcode 753
下一篇:DP打卡日记
🔗
 楼主| goodstudy111 2019-7-29 20:40:27 | 只看该作者
全局:
我发现问题了!!!是char[][] grid,所以char[][] grid == '0'。哭了,我太蠢了
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表