员工重要性_图像渲染
员工的重要性
class Solution {
public int DFS(Map<Integer, Employee> info, int id){
Employee curE = info.get(id); //先获取当前员工!
int curSum = curE.importance; //获取当前员工重要度!
for(int curId : curE.subordinates) {
curSum += DFS(info, curId); //保存当前员工,和下属的重要度!
}
return curSum;//返回结果!
}
public int getImportance(List<Employee> employees, int id) {
if(employees.isEmpty())
return 0;
//将 employees存放在 HashMap中 键值对的形式,便于遍历寻找!
Map<Integer, Employee> info = new HashMap<>();
for(Employee e : employees)//一个个保存!
info.put(e.id, e);
return DFS(info, id);//深度遍历 info!
}
} 图像渲染
class Solution {
//标记 上下左右四个方向!
int[][] nextP = {{1,0},{-1,0},{0,-1},{0,1}};
public int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
int row = image.length;
int col = image[0].length;
//保存需要改变的颜色!
int oldColor = image[sr][sc];
//改变该位置颜色
image[sr][sc] = newColor;
for(int i = 0;i<nextP.length;i++){
//获取下一个位置的坐标!
int nextx = sr + nextP[i][0];
int nexty = sc + nextP[i][1];
if(nextx>=row||nextx<0||nexty>=col||nexty<0){
//越界
continue;
}
if(image[nextx][nexty]==oldColor&&image[nextx][nexty]!=newColor){
//下一个位置需要改变颜色!
floodFill(image,nextx,nexty,newColor);
}
}
return image;
}
} 类似题型
//思路: 如果岛屿的一条边相邻位置是水域或者边界周长就加一!
// 就是 (nextx,nexty) 下一个位置坐标是 0 或者 越界 就加一!
class Solution {
int[][] nextP = {{1,0},{-1,0},{0,-1},{0,1}};
public int DSF(int[][] grid,int row,int col,int sr,int sc){
int result = 0;//保存周长结果!
grid[sr][sc] = 2;//标记 该位置走过!
for(int i = 0;i < nextP.length;i++){
int nextx = sr + nextP[i][0];
int nexty = sc + nextP[i][1];
if(nextx>=row||nextx<0||nexty>=col||nexty<0){
//越界 周长加一!
result++;
continue;
}
if(grid[nextx][nexty]==0){
//水域 周长加一!
result++;
continue;
}
if(grid[nextx][nexty]==1){
//陆地继续深度遍历!
result += DSF(grid,row,col,nextx,nexty);
}
}
return result;
}
public int islandPerimeter(int[][] grid) {
int row = grid.length;
int col = grid[0].length;
int result = 0;
for(int i = 0;i< row;i++){
for(int j = 0;j< col;j++){
if(grid[i][j]==1){
result += DSF(grid,row,col,i,j);
}
}
}
return result;
}
} #笔试#