leetcode-1162

这题典型的广度搜索,但是如何理解呢,对于这种宏观问题,我们不能死扣细节,否则铁写不出来,比如你死扣每条路径,那么问题来了,重复的咋办?所以丢掉细节,就给一个广度搜索的框架。还有个重要的一点是,啥叫最远,题解某人写的不错,你扔石头,哪边水波最后到,说明就是最远的。

所以一条路径走到底的最后一个,绝对就是最长的。

type Point struct {
    X int
    Y int
}

func maxDistance(grid [][]int) int {
    var queue []*Point
    for i := 0; i < len(grid); i++ {
        for j := 0; j < len(grid[0]); j++ {
            if grid[i][j] == 1 {
                queue = append(queue, &Point{i, j})
            }
        }
    }
    if len(queue) == 0 || len(queue) == len(grid)*len(grid[0]) {
        return -1
    }

    ans := 0
    d := [4][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
    for len(queue) > 0 {
        ans++
        tempQue := queue
        queue = nil
        for len(tempQue) > 0 {
            p := tempQue[0]
            tempQue = tempQue[1:]
            for i := 0; i < 4; i++ {
                x := p.X + d[i][0]
                y := p.Y + d[i][1]
                if x < 0 || x >= len(grid) || y < 0 || y >= len(grid[0]) || grid[x][y] != 0 {
                    continue
                }
                queue = append(queue, &Point{x, y})
                grid[x][y] = 2
            }
        }
    }
    return ans-1
}

end

 

猜你喜欢

转载自www.cnblogs.com/CherryTab/p/12595923.html