您的位置:首页 > 其它

题目:岛屿的个数

2015-08-19 19:19 183 查看
给一个01矩阵,求不同的岛屿的个数。

0代表海,1代表岛,如果两个1相邻,那么这两个1属于同一个岛。我们只考虑上下左右为相邻。

您在真实的面试中是否遇到过这个题?

Yes

哪家公司问你的这个题?
Airbnb
Alibaba
Amazon Apple
Baidu Bloomberg
Cisco Dropbox
Ebay Facebook
Google Hulu
Intel Linkedin
Microsoft NetEase
Nvidia Oracle
Pinterest Snapchat
Tencent Twitter
Uber Xiaomi
Yahoo Yelp
Zenefits
感谢您的反馈

样例

在矩阵:

[
[1, 1, 0, 0, 0],
[0, 1, 0, 0, 1],
[0, 0, 0, 1, 1],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 1]
]

中有
3
个岛.

相关题目 Expand

3
(union-find)
困难 岛屿的个数II 11 %

public class Solution {

/**

* @param grid a boolean 2D matrix

* @return an integer

*/

public int numIslands(boolean[][] grid) {

// Write your code here

if (grid == null || grid.length == 0) {

return 0;

}

int m = grid.length;

int n = grid[0].length;

boolean[][] visited = new boolean[m]
;// true表示访问过,false表示没有访过

for(int i=0;i<m;i++){

for(int j=0;j<n;j++){

visited[i][j] = false;

}

}

int res = 0;

for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++) {

if (grid[i][j] && !visited[i][j]) {

DPSlands(grid, visited, i, j);

res++;

}

}

}

return res;

}

public void DPSlands(boolean[][] grid, boolean[][] visited, int i, int j) {

if (i < 0 || i >= grid.length) {

return;

}

if (j < 0 || j >= grid[0].length) {

return;

}

if (!grid[i][j] || visited[i][j]) {

return;

}

visited[i][j] = true;

DPSlands(grid, visited, i - 1, j);

DPSlands(grid, visited, i, j - 1);

DPSlands(grid, visited, i + 1, j);

DPSlands(grid, visited, i, j + 1);

}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: