Grid Challenge
HackerRank 問題: Grid Challenge
Categories:
Question
Given a square grid of characters in the range ascii[a-z], rearrange elements of each row alphabetically, ascending. Determine if the columns are also in ascending alphabetical order, top to bottom. Return YES if they are or NO if they are not.
Answer
<?php
/*
* Complete the 'gridChallenge' function below.
*
* The function is expected to return a STRING.
* The function accepts STRING_ARRAY grid as parameter.
*/
function gridChallenge($string_grid_list) {
// sort string, make sure y-axis is ascending alphabetical
foreach ($string_grid_list as $key => &$string) {
$string_array = str_split($string);
sort($string_array, SORT_STRING);
$string = implode($string_array);
}
$length_of_grid = count($string_grid_list);
$max_x_check_index = $length_of_grid - 1;
// set default is ascending alphabetical
$is_ascending_alphabetical = true;
// search the x-axis to make sure is ascending alphabetical
for ($y_index = 0; $y_index < $length_of_grid; $y_index++) {
for ($x_index = 0; $x_index < $max_x_check_index; $x_index++) {
if (ord($string_grid_list[$x_index][$y_index]) > ord($string_grid_list[$x_index+1][$y_index])) {
// if current alphabet is bigger than next alphabet, so it's not ascending alphabetical
$is_ascending_alphabetical = false;
break;
}
}
if (!$is_ascending_alphabetical) {
// if not ascending, break the loop
break;
}
}
// set return value
$type_of_ascending_alphabetical = 'YES';
if (!$is_ascending_alphabetical) {
$type_of_ascending_alphabetical = 'NO';
}
return $type_of_ascending_alphabetical;
}
$fptr = fopen(getenv("OUTPUT_PATH"), "w");
$t = intval(trim(fgets(STDIN)));
for ($t_itr = 0; $t_itr < $t; $t_itr++) {
$n = intval(trim(fgets(STDIN)));
$grid = array();
for ($i = 0; $i < $n; $i++) {
$grid_item = rtrim(fgets(STDIN), "\r\n");
$grid[] = $grid_item;
}
$result = gridChallenge($grid);
fwrite($fptr, $result . "\n");
}
fclose($fptr);