LeetCode200 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:

Input:
11110
11010
11000
00000

Output: 1

Example 2:

Input:
11000
11000
00100
00011

Output: 3

题源:here;完整实现:here

题外话:

终于写完200道了!虽然中间还是有一些题没有做(因为收费和语言的问题),但是我决定之后的题就没有完整实现这个项目了,即开始在线编程了,这还是一个不小的挑战啊。

思路:

这是一个典型的回溯算法来解决的问题,我们需要做的就是尝试每一种可能的解决方案,当然,对于已经遍历了的数需要做及时的状态记录。代码如下:

class Solution {
public:
	void helper(vector<vector<char>>& grid, int i, int j) {
		int m = int(grid.size()), n = int(grid[0].size());
		grid[i][j] = '2';
		if (i - 1 >= 0 && grid[i - 1][j] == '1') helper(grid, i - 1, j);
		if (i + 1 < m && grid[i + 1][j] == '1') helper(grid, i + 1, j);
		if (j - 1 >= 0 && grid[i][j - 1] == '1') helper(grid, i, j - 1);
		if (j + 1 < n && grid[i][j + 1] == '1') helper(grid, i, j + 1);
		return;
	}
	int numIslands(vector<vector<char>>& grid) {
		int res(0);
		int m = int(grid.size()), n = int(grid[0].size());
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (grid[i][j] == '1') {
					res++;
					helper(grid, i, j);
				}
			}
		}
		return res;
	}
};

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/88576117