【Leetcode】Number of Islands

题目链接:https://leetcode.com/problems/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.

Example 1:

11110
11010
11000
00000

Answer: 1

Example 2:

11000
11000
00100
00011

Answer: 3

思路:

实质是求无向图中连通图的个数。dfs bfs都可以。
前几天正好做了 http://blog.csdn.net/yeqiuzs/article/details/51546155 这道题,就在这题的解法上稍微改动了一下。。

算法:

public class Solution {
    HashMap<Integer, List<Integer>> maps = new HashMap<Integer, List<Integer>>();// 无向图的邻接表
	int[] visited;

	public int numIslands(char[][] matrix) {
		if (matrix.length == 0)
			return 0;

		int rows = matrix.length, cols = matrix[0].length;
		visited = new int[rows * cols];// 访问记录

		// 初始化邻接表
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if(matrix[i][j]=='0'){
					continue;
				}
				List<Integer> neibors = new LinkedList<Integer>();
				if (i - 1 >= 0 && matrix[i - 1][j] =='1') {// 上
					neibors.add((i - 1) * cols + j);
				}
				if (i + 1 < rows && matrix[i + 1][j]=='1') {// 下
					neibors.add((i + 1) * cols + j);
				}
				if (j - 1 >= 0 && matrix[i][j - 1] =='1') {// 左
					neibors.add(i * cols + (j - 1));
				}
				if (j + 1 < cols && matrix[i][j + 1]=='1') {// 右
					neibors.add(i * cols + (j + 1));
				}
				maps.put(i * cols + j, neibors);
				visited[i * cols + j] = 0;
			}

		}
		int count = 0;//连通图个数
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				if (visited[i * cols + j] == 0&&matrix[i][j]=='1') {// 没访问过
					dsp(i * cols + j);
					count++;
				}
			}
		}
		return count;
	}

	public void dsp(int s) {
		if (visited[s] == 1)//已经访问过
			return;
		visited[s] = 1;
		List<Integer> neibors = maps.get(s);
		for (int n : neibors) {
			dsp(n);
		}
	}
}


你可能感兴趣的:(【Leetcode】Number of Islands)