一个简单的解决方案是创建一个数组Room
,或者一个数组Room *
然后,您可以在数组中循环搜索,直到找到搜索值为 的房间x
,或者到达数组的末尾。
如果您从初始房间开始,您可以尝试链表的递归搜索。
但是,我们必须在 struct Room 中添加一个 bool 以避免无限搜索,因为您的房间可能会像这样相互循环:
O--O
| |
O--O
O : room, - and | : link between rooms
该checked
值应false
在开始搜索之前初始化,并且该参数true
在房间被检查一次时获取。
原则 :
Room* search_room (int x_search, Room* current_room)
{
//if current_room is NULL, return NULL
//if checked is true, return NULL
//checked becomes true
//if current_room->x equals x_search, return current_room
//store the result of search_room(x_search, current_room->north) somewhere
//if it's not null, return what it has returned
//if not, then proceed to the store and check of the 3 others calls :
//search_room(x_search, current_room->east)
//search_room(x_search, current_room->south)
//search_room(x_search, current_room->west)
//if all the 4 calls returned NULL, return NULL
}