给你一份航线列表 tickets
,其中 tickets[i] = [fromi, toi]
表示飞机出发和降落的机场地点。请你对该行程进行重新规划排序。
所有这些机票都属于一个从 JFK
(肯尼迪国际机场)出发的先生,所以该行程必须从 JFK
开始。如果存在多种有效的行程,请你按字典排序返回最小的行程组合。
- 例如,行程
["JFK", "LGA"]
与["JFK", "LGB"]
相比就更小,排序更靠前。
假定所有机票至少存在一种合理的行程。且所有的机票 必须都用一次 且 只能用一次。
#include <stdbool.h>
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "stdbool.h"
char **result;
bool *used;
int g_found;
int cmp(const void *str1, const void *str2)
{
const char **tmp1 = *(char**)str1;
const char **tmp2 = *(char**)str2;
if (strcmp(tmp1[0], tmp2[0]) == 0) {
return strcmp(tmp1[1], tmp2[1]);
}
return strcmp(tmp1[0], tmp2[0]);
}
void backtracting(char *** tickets, int ticketsSize, int* returnSize, char *start, char **result, bool *used)
{
if (*returnSize == ticketsSize + 1) {
g_found = 1;
return;
}
for (int i = 0; i < ticketsSize; i++) {
if ((used[i] == false) && (strcmp(start, tickets[i][0]) == 0)) {
result[*returnSize] = (char*)malloc(sizeof(char) * 4);
memcpy(result[*returnSize], tickets[i][1], sizeof(char) * 4);
(*returnSize)++;
used[i] = true;
/*if ((*returnSize) == ticketsSize + 1) {
return;
}*/
backtracting(tickets, ticketsSize, returnSize, tickets[i][1], result, used);
if (g_found) {
return;
}
(*returnSize)--;
used[i] = false;
}
}
return;
}