[Code] number of islands

Topic link: https: //leetcode-cn.com/problems/number-of-islands/submissions/

#include<stdio.h>

// 方向分别对应上下左右
int directon[4][2] = { {0, 1}, {0, -1}, {-1, 0}, {1, 0} };

// dfs的作用就是把一个岛屿的所有点全部给置2
void dfs(char** grid, int gridSize, int* gridColSize, int x, int y)
{
	// 递归结束条件,(1)已经遍历过2 (2)非陆地的点0
	if (grid[x][y] != '1') {
		return;
	}

	// 能走到这里的一定是一个1的点,所以在这里需要置位2
	grid[x][y] = '2';

	// 从点[x , y]开始向四个方向递归遍历置位为2,注意x y可能和i j表示含义有冲突,不要和坐标系弄混
	for (int i = 0; i < 4; i++) {
		int nextX = x + directon[i][0];
		int nextY = y + directon[i][1];

		// 边界判断,不判断会有运行错误
		if (nextX < 0 || nextX >= gridSize || nextY < 0 || nextY >= *gridColSize) {
			continue;
		}

		dfs(grid, gridSize, gridColSize, nextX, nextY);
	}

}




int numIslands(char** grid, int gridSize, int* gridColSize)
{
	int count = 0;


	if (gridSize == 0 || grid == NULL) {
		return 0;
	}

	for (int i = 0; i < gridSize; i++) {
		for (int j = 0; j < *gridColSize; j++) {
			// 地图由0 1 2组成 0表示不需要进行dfs搜索 1表示需要dfs搜索 2表示已经搜索过
			if (grid[i][j] == '1') {
				dfs(grid, gridSize, gridColSize, i, j);
				count++;
			}
		}
	}

	return count;
}


Published 46 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/zzy296753977/article/details/103949683