Leetcode-Number of Islands

今天看到Leetcode又有新题,故着手去做。题目比较简单,就是dfs或bfs的应用。

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.

题意:给定一个2维的网格地图,地图上为字符“1”或“0”,其中“1”为陆地,“0”为水域,默认地图周围都是由水构成。相连的陆地算作一个岛屿,求出地图中的岛屿总数。比如:

11110

11010

11000

00000

为1个岛屿。

11000

11000

00100

00011

为3个岛屿。

分析:只需要对每一个陆地区域做一次dfs,每次dfs中将已经遍历的陆地网格“1”变为水域网格“0”(防止再次遍历导致重复)。对每次dfs计数,总共dfs的次数即为岛屿总数。应注意,grid为空的特殊情况应该排除

AC代码:

class Solution {
public:
    int numIslands(vector<vector<char>> &grid) {
        int row = grid.size();
        if (!row) return 0;
        int col = grid[0].size();
        int count = 0;

        for (unsigned i = 0; i != row; ++i) {
        	for (unsigned j = 0; j != col; ++j) {
        		if (grid[i][j] == '1') {
        			dfs(grid, i, j); ++count;
        		}
        	}
        }

        return count;
    }
    void dfs(vector<vector<char>> &grid, unsigned i, unsigned j) {
    	int dx[4] = {1, 0, -1, 0};
    	int dy[4] = {0, 1, 0, -1};
    	int row = grid.size(), col = grid[0].size();
    	grid[i][j] = '0';

    	for (int k = 0; k != 4; ++k) {
    		int new_i = i + dx[k], new_j = j + dy[k];
    		if (new_i >=0 && new_i < row && new_j >= 0 && new_j < col && grid[new_i][new_j] == '1')
    			dfs(grid, new_i, new_j);
    	}
    }
};
如代码或分析有误,请批评指正,谢谢!


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值