js 图的遍历

690 阅读2分钟

广度优先搜索

力扣题目
简书关于搜索的讲解

以上内容就不做说明了,大神写的非常的清楚明了了。一下是用js实现的搜索

知识点
  1. 用一个viseted保存访问过的节点,用一个队列保存需要遍历查找的节点(坐标),队列空了的时候表示查找完成。
  2. viseted使用map,键为横纵坐标,值为是否访问过,访问过标记为true之后就不用访问了。
  3. 队列初始值就是给定的坐标,循环时候,先队头出列,队头为当前节点;查找当前节点上下左右节点,如果存在节点,并且符合条件且没访问过的,添加到队列。
  4. 不断重复2的队头出列,符合条件的节点入列,就能访问到所有节点。最后就是所有节点都出列,循环结束。

题目一

油漆桶:指定一个坐标,将与坐标相连的所有坐标的颜色改为指定颜色

function fn(image, sr, sc, newColor) {
    let visited = new Map();
    let queue = [`${sr},${sc}`];

    while (queue.length>0){
        // 当前访问的节点
        let curVisit = queue.shift();
        let [pl, pr] = curVisit.split(',');
        pl = parseInt(pl);
        pr = parseInt(pr);
        visited.set(`${pl},${pr}`, true);

        let oldColor = image[pl][pr];

        // 将所有相邻且没访问过的节点添加到队列
        if(image[pl-1] && image[pl-1][pr] === oldColor && !visited.get(`${pl-1},${pr}`)){
            queue.push(`${pl-1},${pr}`);

        }
        if(image[pl+1] && image[pl+1][pr] === oldColor && !visited.get(`${pl+1},${pr}`)){
            queue.push(`${pl+1},${pr}`)
        }
        if(image[pl] && image[pl][pr-1] === oldColor && !visited.get(`${pl},${pr-1}`)){
            queue.push(`${pl},${pr-1}`)
        }
        if(image[pl] && image[pl][pr+1] === oldColor && !visited.get(`${pl},${pr+1}`)){
            queue.push(`${pl},${pr+1}`)
        }
        image[pl][pr] = newColor;
    }
    return image
}
let result = fn([[1,1,1],[1,1,0],[1,0,1]], 1, 1, 2);

console.log(result)

题目二

最大岛屿面积:找到所有岛屿中面积最大的,返回面积

var maxAreaOfIsland = function(grid) {
    let maxVal = 0
    for(let i=0;i<grid.length;i++){
        for(let j=0;j<grid[i].length;j++){
            maxVal =  Math.max(maxVal, dfs(i, j))
        }
    }
    return maxVal

    function dfs(x, y) {
        if(x<0 || x>=grid.length || y<0 || y>=grid[0].length || grid[x][y] === 0){
            return 0;
        }
        let total = 1;
        grid[x][y] = 0;
        let temp1 = [0,0,1,-1];
        let temp2 = [1,-1,0,0];
        for(let i=0;i<4;i++){
            total += dfs(x + temp1[i], y + temp2[i])
        }
        return total;
        }
};