zoukankan      html  css  js  c++  java
  • Java for LeetCode 200 Number of Islands

    Given a 2d grid map of '1's (land) and '0's (water), count 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.

    解题思路:

    参考Java for LeetCode 130 Surrounded Regions BFS即可

    JAVA实现如下:

        public int numIslands(char[][] grid) {
    		int res = 0;
    		for (int i = 0; i < grid.length; i++)
    			for (int j = 0; j < grid[0].length; j++)
    				if (grid[i][j] == '1') {
    					grid[i][j] = '0';
    					bfs(grid, i * grid[0].length + j);
    					res++;
    				}
    		return res;
    	}
    
    	public static void bfs(char[][] grid, int num) {
    		Queue<Integer> queue = new LinkedList<Integer>();
    		queue.add(num);
    		while (!queue.isEmpty()) {
    			num = queue.poll();
    			int row = num / grid[0].length;
    			int col = num - row * grid[0].length;
    			if (row - 1 >= 0 && grid[row - 1][col] == '1') {
    				grid[row - 1][col] = '0';
    				queue.add(num - grid[0].length);
    			}
    			if (row + 1 <= grid.length - 1 && grid[row + 1][col] == '1') {
    				grid[row + 1][col] = '0';
    				queue.add(num + grid[0].length);
    			}
    			if (col - 1 >= 0 && grid[row][col - 1] == '1') {
    				grid[row][col - 1] = '0';
    				queue.add(num - 1);
    			}
    			if (col + 1 <= grid[0].length - 1 && grid[row][col + 1] == '1') {
    				grid[row][col + 1] = '0';
    				queue.add(num + 1);
    			}
    		}
    	}
    
  • 相关阅读:
    相关书籍下载2
    神奇的null和undefined
    相关书籍下载1
    微信小程序之for循环
    渐变(Gradients)
    模拟今日头条顶部导航菜单
    网格布局之相关特性
    网格布局之合并单元格
    网格布局
    Linux常用命令
  • 原文地址:https://www.cnblogs.com/tonyluis/p/4558750.html
Copyright © 2011-2022 走看看