Skip to content

Instantly share code, notes, and snippets.

@ounziw
Created November 17, 2014 08:31
Show Gist options
  • Save ounziw/06373bb6c717c73cb850 to your computer and use it in GitHub Desktop.
Save ounziw/06373bb6c717c73cb850 to your computer and use it in GitHub Desktop.
nagoya php 第7回のどうかく?問題。次のルートへのデータを、再帰的に処理する
<?php
$routes = array(
1 => array('a','g'),
2 => array('d','h'),
3 => array('b','f'),
'a' => array('b'),
'b' => array('c',5),
'c' => array(4,6),
'd' => array('c','e'),
'e' => array(5),
'f' => array('g'),
'g' => array('c','e','h'),
'h' => array(4,'i'),
'i' => array(6),
);
$input = 'ag';
$input_array = str_split($input);
// 通れない道を削除する
foreach ($input_array as $arr) {
unset($routes[$arr]);
}
/**
* @param str $input
* @return array
*/
function get_next_node($input) {
global $routes;
if (array_key_exists($input, $routes)) {
return $routes[$input];
} else {
return false;
}
}
$ok = array();
/**
* 次のルートを探す
*/
function get_route($input,$start) {
global $ok;
if (check_456($input)) {
$ok[$start][] = $input;
} else {
$next_way = get_next_node($input);
if ($next_way) {
foreach ($next_way as $arr) {
get_route($arr,$start);
}
}
}
}
/**
* 4,5,6だったらゴール
*/
function check_456($input) {
if ($input == 4) {
return 4;
}
if ($input == 5) {
return 5;
}
if ($input == 6) {
return 6;
}
return false;
}
get_route(1,1);
get_route(2,2);
get_route(3,3);
var_dump($ok);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment