Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

529-扫雷游戏 #37

Open
YBFACC opened this issue Aug 20, 2020 · 0 comments
Open

529-扫雷游戏 #37

YBFACC opened this issue Aug 20, 2020 · 0 comments

Comments

@YBFACC
Copy link
Owner

YBFACC commented Aug 20, 2020

529-扫雷游戏

这是一题类岛屿问题,分析情况:

  • 踩到未挖出的雷,改为‘X'直接结束游戏
  • 踩到空白位置先验证附近8格是否有雷
    • 如果没雷就改为‘B’,继续揭示其他8格
    • 如果有雷就改为雷数,结束

这题可以去重,可以避免走重复的路径

function updateBoard(board: string[][], click: number[]): string[][] {
  const x = click[0]
  const y = click[1]
  if (board[x][y] === 'M') {
    board[x][y] = 'X'
    return board
  }
  const rowLimit = board.length
  const colLimit = board[0].length
  const visited = new Set()
  const ways = [
    [-1, -1],
    [-1, 0],
    [-1, 1],
    [0, -1],
    [0, 1],
    [1, -1],
    [1, 0],
    [1, 1]
  ]
  const dfs = function (x: number, y: number): number {
    if (board[x][y] === 'M' || board[x][y] === 'X') return 1
    const str = `${x},${y}`
    if (board[x][y] !== 'E' || visited.has(str)) return 0
    visited.add(str)
    let count = 0
    for (const way of ways) {
      const r = way[0] + x
      const c = way[1] + y
      if (r < 0 || r >= rowLimit || c < 0 || c >= colLimit) continue
      if (board[r][c] === 'M' || board[r][c] === 'X') count++
    }
    if (count === 0) {
      for (const way of ways) {
        const r = way[0] + x
        const c = way[1] + y
        if (
          r < 0 ||
          r >= rowLimit ||
          c < 0 ||
          c >= colLimit ||
          visited.has(`${r},${c}`)
        )
          continue
        dfs(r, c)
      }
      board[x][y] = 'B'
    } else {
      board[x][y] = count + ''
    }
    return 0
  }
  dfs(x, y)
  return board
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant