[JavaScript 刷题] 搜索 - 被围绕的区域,leetcode 130

Posted GoldenaArcher

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[JavaScript 刷题] 搜索 - 被围绕的区域,leetcode 130相关的知识,希望对你有一定的参考价值。

[javascript 刷题] 搜索 - 被围绕的区域,leetcode 130

题目地址:130. Surrounded Regions

题目如下:

Given an m x n matrix board containing 'X' and 'O', capture all regions that are 4-directionally surrounded by 'X'.

A region is captured by flipping all 'O's into 'X's in that surrounded region.

解题思路

嗯,这道题刚开始想岔了,就像直接开始跳过边框从中间开始填充,然后发现这个问题还挺难回答的:

怎么正确的判断当前区域没有与边界相连?

图如下:

但是换言之,如果从四边开始进行 DFS 搜索,边框上的 'O' 及其相关 'O' 进行填充,那么处理起来就很简单了。

如:

随后再遍历整个数组,进行以下翻转:

  • O - X
  • X - X
  • K - O

即可以完成实现。

使用 JavaScript 解题

const directions = [
  [1, 0],
  [-1, 0],
  [0, 1],
  [0, -1],
];

const isIllegalPos = (board, row, col) => 
  return row < 0 || row >= board.length || col < 0 || col >= board[row].length;
;

const dfs = (board, row, col) => 
  if (
    isIllegalPos(board, row, col) ||
    board[row][col] === "X" ||
    board[row][col] === "K"
  )
    return;

  board[row][col] = "K";

  for (const [r, c] of directions) 
    dfs(board, row + r, col + c);
  
;

/**
 * @param character[][] board
 * @return void Do not return anything, modify board in-place instead.
 */
var solve = function (board) 
  if (!board || board.length < 2 || board[0].length < 2) return;
  // top and bottom
  for (let i = 0; i < board[0].length; i++) 
    dfs(board, 0, i);
    dfs(board, board.length - 1, i);
  

  // left and right
  for (let i = 1; i < board.length - 1; i++) 
    dfs(board, i, 0);
    dfs(board, i, board[0].length - 1);
  

  for (let row = 0; row < board.length; row++) 
    for (let col = 0; col < board[row].length; col++) 
      if (board[row][col] === "O") board[row][col] = "X";
      else if (board[row][col] === "K") board[row][col] = "O";
    
  
;

以上是关于[JavaScript 刷题] 搜索 - 被围绕的区域,leetcode 130的主要内容,如果未能解决你的问题,请参考以下文章

java刷题--130被围绕的区域

[JavaScript 刷题] 搜索 - DFS(深度优先搜索)

[JavaScript 刷题] 搜索 - 单词搜索, leetcode 79

[JavaScript 刷题] 搜索 - 单词搜索, leetcode 79

[JavaScript 刷题] 搜索 - 单词搜索, leetcode 79

[JavaScript 刷题] 二分搜索 - 搜索二维矩阵, leetcode 74