[LeetCode 最短的桥 && 省份数量] | 刷题打卡

210 阅读1分钟

934. 最短的桥

leetcode-cn.com/problems/sh…

  • dfs + bfs
/**
 * @param {number[][]} A
 * @return {number}
 */
var shortestBridge = function (A) {

    const direction = [[1, 0], [0, 1], [-1, 0], [0, -1]]
    const width = A.length
    const height = A[0].length
    let flag = true
    let stack = []
    let counter = 0
    for (let i = 0; i < width; i++) {
        for (let j = 0; j < height; j++) {
            if (A[i][j] === 1 && flag) {
                flag = false
                dfs(i, j)
            }
        }
    }
    // 标记为2的岛屿同时向1扩散
    while (stack.length) {
        counter++
        const size = stack.length
        for (let j = 0; j < size; j++) {
            const [x, y] = stack.shift()
            for (let m = 0; m < direction.length; m++) {
                const nowX = x + direction[m][0]
                const nowY = y + direction[m][1]
                if (nowX >= 0 && nowY >= 0 && nowX < width && nowY < height) {
                    if (A[nowX][nowY] === 0 ) {
                        A[nowX][nowY] = 2
                        stack.push([nowX, nowY])
                    } else if (A[nowX][nowY] === 1) {
                        return counter -1
                    }
                }

            }
        }
    }

    function dfs(i, j) {
        if (i < 0 || i > (width - 1) || j < 0 || j > (height - 1)) {
            return
        }
        if (A[i][j] === 1) {
            A[i][j] = 2
            stack.push([i, j])
            for (let m = 0; m < direction.length; m++) {
                const nowX = i + direction[m][0]
                const nowY = j + direction[m][1]
                dfs(nowX, nowY)
            }
        }
    }


};

547. 省份数量

leetcode-cn.com/problems/nu…

  • 并查集
  • 将所有联通的城市合并为一个省份,然后球省份的数量
/**
 * @param {number[][]} isConnected
 * @return {number}
 */
class DisJoinSet{
    data = []
    constructor(n){
        for(let i=0;i<n;i++){
            this.data[i] = i
        }
    }

    merge(v1,v2){
        const p1 = this.find(v1)
        const p2 = this.find(v2)
        if(p1 === p2){
            return
        }
        for(let i=0;i<this.data.length;i++){
            if(this.data[i] === p1){
                this.data[i] = p2
            }
        }
    }

    find(target){
        return this.data[target]
    }
}
var findCircleNum = function(isConnected) {
    const djs = new DisJoinSet(isConnected.length)
    for(let i=0;i<isConnected.length;i++){
        for(let j=0;j<isConnected.length;j++){
            if(isConnected[i][j] ===1){
                djs.merge(i,j)
            }
        }
    }
    return djs.data.filter((v, i) => v === i).length
};