Skip to content

Instantly share code, notes, and snippets.

@scottfoster
Created September 1, 2025 09:27
Show Gist options
  • Select an option

  • Save scottfoster/8068f1e802fd7803223a3b7a83bd2d06 to your computer and use it in GitHub Desktop.

Select an option

Save scottfoster/8068f1e802fd7803223a3b7a83bd2d06 to your computer and use it in GitHub Desktop.
Imagine a simplified version of the game Battleship played on a 2D grid. The grid represents the sea, and each cell can either be empty (.) or contain a part of a ship (X). Ships are placed horizontally or vertically, and there are no adjacent ships. Given a grid, count the number of battleships in it. Extra credit: can you make a layout generat…
<?php
function numberOfShips(array $ships): int
{
$totalShips = 0;
$rows = count($ships);
$cols = count($ships[0]);
for ($r = 0; $r < $rows; $r++)
{
for ($c = 0; $c < $cols; $c++)
{
if ($ships[$r][$c] !== 'X') continue;
$checkUpShip = $r > 0 && $ships[$r-1][$c] == 'X';
$checkLeftShip = $c > 0 && $ships[$r][$c-1] == 'X';
if(!$checkUpShip && !$checkLeftShip)
{
$totalShips++;
}
}
}
return (int)$totalShips;
}
$ships = [
['X', 'X', '.', 'X'],
['.', '.', '.', 'X'],
['.', '.', '.', 'X'],
['.', '.', '.', '.'],
];
echo numberOfShips($ships) . PHP_EOL; // 2
$ships = [
['X', 'X', '.', 'X'],
['.', '.', '.', 'X'],
['X', '.', '.', 'X'],
['X', '.', '.', '.'],
];
echo numberOfShips($ships) . PHP_EOL; // 3
$ships = [
['X', '.', '.', '.'],
['X', '.', '.', '.'],
['.', 'X', 'X', 'X'],
['.', '.', '.', '.'],
];
echo numberOfShips($ships) . PHP_EOL; // 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment