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);
			}
		}
	}
原文地址:https://www.cnblogs.com/tonyluis/p/4558750.html