Given a 2D board containing'X'and'O', capture all regions surrounded by'X'.
A region is captured by flipping all'O's into'X's in that surrounded region .
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
给一个二维图由X和O组成,获取所有被X包围的区域,把其中的O改为X。
思路:
从最边缘开始,获取是O的,把她改为A,然后对他的邻居进行递归搜索。
<?php
function solve($arrBoard) {
if (empty($arrBoard)) {
return array();
}
$x = count($arrBoard);
$y = count($arrBoard[0]);
for ($j = 0; $j < $y; $j ++) {
//第一行
notArround($arrBoard, 0, $j);
//最后一行
notArround($arrBoard, $x - 1, $j);
}
for ($i = 0; $i < $x; $i ++) {
//第一列
notArround($arrBoard, $i, 0);
//最后一列
notArround($arrBoard, $i, $y - 1);
}
for ($i = 0; $i < $x; $i ++) {
for ($j = 0; $j < $y; $j ++) {
if ($arrBoard[$i][$j] === 'O') {
$arrBoard[$i][$j] = 'X';
}
if ($arrBoard[$i][$j] === 'A') {
$arrBoard[$i][$j] = 'O';
}
}
}
return $arrBoard;
}
function notArround(&$arrBoard, $i, $j) {
if (!isset($arrBoard[$i][$j]) || $arrBoard[$i][$j] !== 'O') {
return;
}
$arrBoard[$i][$j] = 'A';
notArround($arrBoard, $i + 1, $j);
notArround($arrBoard, $i - 1, $j);
notArround($arrBoard, $i, $j + 1);
notArround($arrBoard, $i, $j - 1);
}
$array = [
['X','X','X','X'],
['X','O','O','X'],
['X','X','O','X'],
['X','O','X','X'],
];
$ret = solve($array);
print json_encode($ret);