博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【leetcode】Number of Islands(middle)
阅读量:5038 次
发布时间:2019-06-12

本文共 2425 字,大约阅读时间需要 8 分钟。

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

 

思路:与的思路是一样的,也可以用广度和深度优先搜索。当遇到1的时候,把区域数加1,并把与这个1相连的整片区域标记为2.

下面的BFS用时25ms,DFS用时16ms

int numIslands(vector
>& grid) { if(grid.empty()) return 0; int num = 0; for(int i = 0; i < grid.size(); ++i) for(int j = 0; j < grid[0].size(); ++j) if(grid[i][j] == '1') { num++; BFS(grid, i, j); } return num; } void BFS(vector
>& grid, int r, int c) { queue
> q; q.push(make_pair(r, c)); while(!q.empty()) { int i = q.front().first; int j = q.front().second; q.pop(); if(i >= 0 && j >= 0 && i < grid.size() && j < grid[0].size() && grid[i][j] == '1') { grid[i][j] = 2; q.push(make_pair(i - 1, j)); q.push(make_pair(i + 1, j)); q.push(make_pair(i, j - 1)); q.push(make_pair(i, j + 1)); } } } void DFS(vector
>& grid, int r, int c) { if(r >= 0 && c >= 0 && r < grid.size() && c < grid[0].size() && grid[r][c] == '1') { grid[r][c] = 2; DFS(grid, r - 1, c); DFS(grid, r + 1, c); DFS(grid, r, c - 1); DFS(grid, r, c + 1); } }

 

很奇怪的是,开始我写的时候BFS多传了一个变量就TLE了??为什么呢??

int numIslands(vector
>& grid) { if(grid.empty()) return 0; int num = 0; for(int i = 0; i < grid.size(); ++i) { for(int j = 0; j < grid[0].size(); ++j) { if(grid[i][j] == '1') BFS(grid, i, j, num); } } return num; } void BFS(vector
>& grid, int r, int c, int &num) { num++; queue
> q; q.push(make_pair(r, c)); while(!q.empty()) { int i = q.front().first; int j = q.front().second; q.pop(); if(i >= 0 && j >= 0 && i < grid.size() && j < grid[0].size() && grid[i][j] == '1') { grid[i][j] = num + 1; q.push(make_pair(i - 1, j)); q.push(make_pair(i + 1, j)); q.push(make_pair(i, j - 1)); q.push(make_pair(i, j + 1)); } } }

 

转载于:https://www.cnblogs.com/dplearning/p/4474842.html

你可能感兴趣的文章
tampermonkey,采用js解析自定义脚本,实现网页列表数据采集分析
查看>>
Linux Kernel 整数溢出漏洞
查看>>
hdu 4001 To Miss Our Children Time
查看>>
jmeter+ant+jenkins 框架搭建(二)
查看>>
多播委托与观察者模式联合使用,以及委托与事件的区别
查看>>
批量get_flag v3
查看>>
[ubuntu]一文解决ubuntu换源相关的所有问题
查看>>
封装与解封装
查看>>
最长英语单词链
查看>>
iOS界面跳转
查看>>
hibernate初学感触
查看>>
【基础】栈和堆的区别
查看>>
棋盘制作
查看>>
global name 'validate_on_submit' is not defined错误
查看>>
叫卖集体土地版“公租房 ” (zz)
查看>>
javascript array操作
查看>>
[AWDwR4] Getting AJAX to work in Rails 3 with jQuery
查看>>
CentOS 安装配置TFTP
查看>>
VMware中ubuntu忘记密码的解决办法
查看>>
navicat for mysql快捷键
查看>>