码迷,mamicode.com
首页 > 其他好文 > 详细

第八篇 LeetCode Number of Islands

时间:2015-12-21 15:43:24      阅读:130      评论:0      收藏:0      [点我收藏+]

标签:

好久没更新了,终于考完了继续回来刷题

岛屿问题属于最基本的DFS, BFS题目 使用DFS时会遇到如果图太大call stack过深的follow up,此时可以转为使用BFS

下一篇Number of Islands II 中将使用另一种Union Find的做法

 

public class Solution {
    public int numIslands(char[][] grid) {
        if (grid == null || grid.length == 0) {
            return 0;
        }
        int result = 0;
        int m = grid.length;
        int n = grid[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                //if gird[i][j] is not visited
                if (grid[i][j] == ‘1‘) {
                    bfs(grid, i, j);
                    result++;
                }
            }
        }
        return result;
    }
    
    private void bfs(char[][] grid, int a, int b) {
        int[] x = {1, 0, -1, 0};
        int[] y = {0, -1, 0, 1};
        grid[a][b] = ‘0‘;
        Queue<Pair> q = new LinkedList<Pair>();
        q.offer(new Pair(a, b));
        while (!q.isEmpty()) {
            Pair p = q.poll();
            for (int i = 0; i < 4; i++) {
                int x1 = p.x + y[i];
                int x2 = p.y + x[i];
                if (x2 >= 0 && x2 < grid[0].length && x1 >= 0 && x1 < grid.length) {
                    if (grid[x1][x2] == ‘1‘) {
                        grid[x1][x2] = ‘0‘;
                        q.offer(new Pair(x1, x2));
                    }
                }
            }
        }
        
        
    }
    
    private class Pair {
        int x;
        int y;
        
        public Pair(int x, int y) {
            this.x = x;
            this.y = y;
        }
    }
    
    private void dfs(char[][] grid, int a, int b) {
        grid[a][b] = ‘0‘;
        int[] x = {1, 0, -1, 0};
        int[] y = {0, -1, 0, 1};
        
        for (int i = 0; i < 4; i++) {
            int x1 = a + y[i];
            int x2 = b + x[i];
            if (x2 >= 0 && x2 < grid[0].length && x1 >= 0 && x1 < grid.length) {
                if (grid[x1][x2] == ‘1‘) {
                    //grid[x1][x2] = ‘0‘;
                    dfs(grid, x1, x2);
                }
            }
        }
    }
}

 

第八篇 LeetCode Number of Islands

标签:

原文地址:http://www.cnblogs.com/ilovenaomi/p/5063395.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!