1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
$matrix = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; |
4
|
|
|
|
5
|
|
|
for ( $row = 0; $row < sizeof( $matrix ); $row++ ) { |
6
|
|
|
for ( $column = 0; $column < sizeof( $matrix[0] ); $column++ ) { |
7
|
|
|
echo $matrix[$row][$column] . " "; |
8
|
|
|
} |
9
|
|
|
echo PHP_EOL; |
10
|
|
|
} |
11
|
|
|
|
12
|
|
|
function findNeighbours ( array $matrix, int $row, int $column ) : array |
13
|
|
|
{ |
14
|
|
|
$neighbours = []; |
15
|
|
|
|
16
|
|
|
for ( $currentRow = $row - 1; $currentRow <= $row + 1; $currentRow++ ) { |
17
|
|
|
for ( $currentColumn = $column - 1; $currentColumn <= $column + 1; $currentColumn++ ) { |
18
|
|
|
if ( isElementInRange( $currentRow, $currentColumn, |
19
|
|
|
$matrix ) && ( $currentRow != $row || $currentColumn != $column ) ) { |
20
|
|
|
$neighbours[] = [ "row" => $currentRow, "column" => $currentColumn ]; |
21
|
|
|
} |
22
|
|
|
} |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
return $neighbours; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
function isElementInRange ( $row, $column, $matrix ) : bool |
29
|
|
|
{ |
30
|
|
|
$inRange = true; |
31
|
|
|
|
32
|
|
|
if ( $row < 0 || $column < 0 ) { |
33
|
|
|
$inRange = false; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
if ( $row > sizeof( $matrix ) - 1 ) { |
37
|
|
|
$inRange = false; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
if ( $column > sizeof( $matrix[0] ) - 1 ) { |
41
|
|
|
$inRange = false; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
return $inRange; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
for ( $row = 0; $row < sizeof( $matrix ); $row++ ) { |
48
|
|
|
for ( $column = 0; $column < sizeof( $matrix[0] ); $column++ ) { |
49
|
|
|
$neighbours = findNeighbours( $matrix, $row, $column ); |
50
|
|
|
echo "neighbours for row $row, column $column are:" . print_r( $neighbours, true ) . PHP_EOL; |
|
|
|
|
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|