200. 岛屿数量
给你一个由 ‘1’(陆地)和 ‘0’(水)组成的的二维网格,请你计算网格中岛屿的数量。
岛屿总是被水包围,并且每座岛屿只能由水平方向和/或竖直方向上相邻的陆地连接形成。
此外,你可以假设该网格的四条边均被水包围。
示例 1:
输入:grid = [
[“1”,“1”,“1”,“1”,“0”],
[“1”,“1”,“0”,“1”,“0”],
[“1”,“1”,“0”,“0”,“0”],
[“0”,“0”,“0”,“0”,“0”]
]
输出:1
来源:力扣(LeetCode)
思路:
遍历二维数组,每当‘1’就让 计数+1,然后用深度优先搜索,所当前的的位置,以及上下左右为
‘1’的位置 递归的赋值为‘0’,这样在遍历二维数组时就能正常的进行岛屿的计数了
这题在深度搜索里算简单的了,我们在进行dfs时只要注意一下边界值就行了
代码:
class Solution {
public:
void dfs(vector<vector<char>>&island, int row, int col)
{
int rowsize = island.size();
int colsize = island[0].size();
//记得赋值为‘0’
island[row][col] = '0';
/*边界条件别忘了*/
//对上下左右进行dfs
if(row-1 >=0 && island[row-1][col] == '1') dfs(island,row-1,col);
if(row+1 <rowsize && island[row+1][col] == '1') dfs(island,row+1,col);
if(col-1 >=0 && island[row][col-1] == '1') dfs(island,row,col-1);
if(col+1 < colsize && island[row][col+1] == '1') dfs(island,row,col+1);
}
int numIslands(vector<vector<char>>& grid) {
int rowsize = grid.size();
int colsize = grid[0].size();
int res = 0;
for(int r = 0;r<rowsize;++r)
{//两个for遍历二维数组
for(int c = 0;c<colsize;++c)
{
if(grid[r][c] == '1')
{
++res;//遇见一次‘1’就+1
dfs(grid,r,c);
}
}
}
return res;
}
};
690. 员工的重要性
给定一个保存员工信息的数据结构,它包含了员工 唯一的 id ,重要度 和 直系下属的 id 。
比如,员工 1 是员工 2 的领导,员工 2 是员工 3 的领导。他们相应的重要度为 15 , 10 , 5 。那么员工 1 的数据结构是 [1, 15, [2]] ,员工 2的 数据结构是 [2, 10, [3]] ,员工 3 的数据结构是 [3, 5, []] 。注意虽然员工 3 也是员工 1 的一个下属,但是由于 并不是直系 下属,因此没有体现在员工 1 的数据结构中。
现在输入一个公司的所有员工信息,以及单个员工 id ,返回这个员工和他所有下属的重要度之和。
来源:力扣(LeetCode)
因为给的数组,所以如果要快速找到对应的员工的话,可以用哈希表来加速查找
class Solution {
int res;
unordered_map<int,Employee*>map;
void dfs(int id)
{
Employee* employee = map[id];
res+=employee->importance;
for(auto subId : employee->subordinates)
dfs(subId);
}
public:
int getImportance(vector<Employee*> employees, int id) {
res = 0;
for(auto &employee : employees)
map[employee->id] = employee;
dfs(id);
return res;
}
};