📜  查找岛屿数量的PHP程序|设置 1(使用 DFS)

📅  最后修改于: 2022-05-13 02:24:09.349000             🧑  作者: Mango

查找岛屿数量的PHP程序|设置 1(使用 DFS)

给定一个布尔二维矩阵,找出岛屿的数量。一组连接的 1 形成一个岛。例如,下面的矩阵包含 5 个岛屿
例子:

Input : mat[][] = {{1, 1, 0, 0, 0},
                   {0, 1, 0, 0, 1},
                   {1, 0, 0, 1, 1},
                   {0, 0, 0, 0, 0},
                   {1, 0, 1, 0, 1} 
Output : 5

这是标准问题的变体:“计算无向图中的连通分量的数量”。
在我们解决问题之前,让我们了解什么是连接组件。无向图的连通分量是一个子图,其中每两个顶点通过一条路径相互连接,并且不与子图之外的其他顶点相连。
例如,下图具有三个连通分量。

PHP
= 0) && ($row < $ROW) &&    
           ($col >= 0) && ($col < $COL) &&    
           ($M[$row][$col] &&
             !isset($visited[$row][$col]));
}
 
// A utility function to do DFS
// for a 2D boolean matrix. It
// only considers the 8 neighbours
// as adjacent vertices
function DFS(&$M, $row, $col,
            &$visited)
{
    // These arrays are used to
    // get row and column numbers
    // of 8 neighbours of a given cell
    $rowNbr = array(-1, -1, -1, 0,
                    0, 1, 1, 1);
    $colNbr = array(-1, 0, 1, -1,
                    1, -1, 0, 1);
 
    // Mark this cell as visited
    $visited[$row][$col] = true;
 
    // Recur for all
    // connected neighbours
    for ($k = 0; $k < 8; ++$k)
        if (isSafe($M, $row + $rowNbr[$k],
                $col + $colNbr[$k], $visited))
            DFS($M, $row + $rowNbr[$k],
                $col + $colNbr[$k], $visited);
}
 
// The main function that returns
// count of islands in a given
// boolean 2D matrix
function countIslands(&$M)
{
    global $ROW, $COL;
     
    // Make a bool array to
    // mark visited cells.
    // Initially all cells
    // are unvisited
    $visited = array(array());
 
    // Initialize count as 0 and
    // traverse through the all
    // cells of given matrix
    $count = 0;
    for ($i = 0; $i < $ROW; ++$i)
        for ($j = 0; $j < $COL; ++$j)
            if ($M[$i][$j] &&
                 !isset($visited[$i][$j])) // If a cell with value 1
            {                               // is not visited yet,
                DFS($M, $i, $j, $visited); // then new island found
                ++$count;                   // Visit all cells in this
            }                               // island and increment
                                           // island count.
 
    return $count;
}
 
// Driver Code
$M = array(array(1, 1, 0, 0, 0),
           array(0, 1, 0, 0, 1),
           array(1, 0, 0, 1, 1),
            array(0, 0, 0, 0, 0),
           array(1, 0, 1, 0, 1));
 
echo "Number of islands is: ",
            countIslands($M);
 
// This code is contributed
// by ChitraNayal
?>


请参阅有关查找岛屿数量的完整文章 |设置 1(使用 DFS)了解更多详情!