【leetcode】 200. Number of Islands
2015-09-21 13:55
323 查看
简单的dfs递归,我们把每个访问到的‘1’,都对其进行dfs,使得与他相邻的‘1’都置为‘0’
/** * @author johnsondu * @problem Number of Islands * @url https://leetcode.com/problems/number-of-islands/ * @timeComlexity O(n^2) * @spaceComplexity O(1) * @strategy See code. */ int dir[4][2] = {1, 0, -1, 0, 0, 1, 0, -1}; class Solution { public: void dfs(int x, int y, int row, int col, vector<vector<char>>& grid) { for(int i = 0; i < 4; i ++) { int tx = x + dir[i][0]; int ty = y + dir[i][1]; if(tx < row && tx >= 0 && ty < col && ty >= 0) { if(grid[tx][ty] == '1') { grid[tx][ty] = '0'; dfs(tx, ty, row, col, grid); } } } } int numIslands(vector<vector<char>>& grid) { int row = grid.size(); if(row == 0) return 0; int col = grid[0].size(); if(col == 0) return 0; int cnt = 0; for(int i = 0; i < row; i ++) for(int j = 0; j < col; j ++) { if(grid[i][j] == '1') { cnt ++; dfs(i, j, row, col, grid); } } return cnt; } };
相关文章推荐
- kmalloc vmalloc kzalloc malloc 和 get_free_page()【转】
- node.js环境搭建
- Shellshock漏洞回顾与分析测试 http://drops.wooyun.org/papers/3268
- 理性
- Google APAC 2016 University Graduates Test Round B解题报告
- 9*9乘法表中for循环中遇到的一点问题
- 会话保持
- OCP-V13-698
- StringUtils中 isNotEmpty 和isNotBlank的区别
- 获取指定字节长度的字符串
- [转] The Single Biggest Obstacle to Trading Success
- ubuntu下用gcc编译c程序文件
- Mac 使用终端关机的命令
- 如何在App中实现朋友圈功能之二快速实现用户信息的自定义——箭扣科技Arrownock
- hdu5452 Minimum Cut(弱数据)
- hdu5452 Minimum Cut(弱数据)
- linux远程下载文件 的两种方法之 ftp命令和scp
- redis启动时警告信息去除及简单安全设置
- 解决Laravel5.1使用composer update时出现Call to undefined method getCachedCompilePath()错误
- UIStackView学习