leetcode1001-网格照明

题目描述

  • n x n 的网格
  • 若干盏灯
  • 若某个灯亮,则这盏灯所在的行、列、斜线、反斜线都亮
  • 有若干个询问,返回某个点亮或灭。询问完,若周围相邻的位置有灯,关闭它们

示例

初始状态

1001-example-01

输入:n = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
输出:[1,0]

第一次查询

1001-example-01-01

第二次查询

1001-example-01-02

题解

  • 思路
    1. 遍历灯,标记灯所在的行、列、两条对角线
    2. 查询,目标的行、列、对角线有标记的,就是亮;如果亮,查询周围,如果有灯,更新标记
func gridIllumination(n int, lamps [][]int, queries [][]int) []int {
    row, col := map[int]map[int]bool{}, map[int]map[int]bool{}
    dg, udg := map[int]map[int]bool{}, map[int]map[int]bool{}
    for _, p := range lamps {
        x, y := p[0], p[1]
        if _, has := row[x]; !has { row[x] = make(map[int]bool) }
        if _, has := col[y]; !has { col[y] = make(map[int]bool) }
        if _, has := dg[y - x]; !has { dg[y - x] = make(map[int]bool) }
        if _, has := udg[y + x]; !has { udg[y + x] = make(map[int]bool) }
        row[x][y] = true
        col[y][x] = true
        dg[y - x][x] = true
        udg[y + x][x] = true
    }

    res := make([]int, len(queries))
    for i, q := range queries {
        x, y := q[0], q[1]
        if len(row[x]) > 0 || len(col[y]) > 0 ||
                len(dg[y - x]) > 0 || len(udg[y + x]) > 0 {
            res[i] = 1
            for a := x - 1; a <= x + 1; a ++ {
                for b := y - 1; b <= y + 1; b ++ {
                    delete(row[a], b)
                    delete(col[b], a)
                    delete(dg[b - a], a)
                    delete(udg[b + a], a)
                }
            }
        } else {
            res[i] = 0
        }
    }
    return res
}
posted @ 2025-08-19 22:56  余越  阅读(7)  评论(0)    收藏  举报