LeetCode //C - 332. Reconstruct Itinerary

332. Reconstruct Itinerary

You are given a list of airline tickets where tickets[i] = [fromi, toi] represent the departure and the arrival airports of one flight. Reconstruct the itinerary in order and return it.

All of the tickets belong to a man who departs from "JFK", thus, the itinerary must begin with "JFK". If there are multiple valid itineraries, you should return the itinerary that has the smallest lexical order when read as a single string.

  • For example, the itinerary ["JFK", "LGA"] has a smaller lexical order than ["JFK", "LGB"].

You may assume all tickets form at least one valid itinerary. You must use all the tickets once and only once.

Example 1:

Input: tickets = [["MUC","LHR"],["JFK","MUC"],["SFO","SJC"],["LHR","SFO"]]
Output: ["JFK","MUC","LHR","SFO","SJC"]

Example 2:

Input: tickets = [["JFK","SFO"],["JFK","ATL"],["SFO","ATL"],["ATL","JFK"],["ATL","SFO"]]
Output: ["JFK","ATL","JFK","SFO","ATL","SFO"]
Explanation: Another possible reconstruction is ["JFK","SFO","ATL","JFK","ATL","SFO"] but it is larger in lexical order.

Constraints:
  • 1 <= tickets.length <= 300
  • tickets[i].length == 2
  • f r o m i . l e n g t h = = 3 from_i.length == 3 fromi.length==3
  • t o i . l e n g t h = = 3 to_i.length == 3 toi.length==3
  • f r o m i a n d t o i c o n s i s t o f u p p e r c a s e E n g l i s h l e t t e r s . from_i and toi consist of uppercase English letters. fromiandtoiconsistofuppercaseEnglishletters.
  • f r o m i ! = t o i from_i != to_i fromi!=toi

From: LeetCode

Link: 332. Reconstruct Itinerary


Solution:

Ideas:
  • Deferred Memory Freeing: The nodes (Node*) in the adjacency list are no longer freed immediately within the DFS loop. Instead, they're freed only after the DFS traversal is complete, preventing use-after-free errors.
  • DFS Stack Handling: The stack is used to manage the DFS iteration, and nodes are correctly removed from the adjacency list as they are processed. The itinerary is built in reverse order and then freed once fully constructed.
Code:
c 复制代码
#define MAX_TICKETS 300
#define MAX_AIRPORTS 26 * 26 * 26 // Assuming three-letter airport codes
#define AIRPORT_CODE_LEN 4

// Node structure for adjacency list
typedef struct Node {
    char airport[AIRPORT_CODE_LEN];
    struct Node* next;
} Node;

// Function to insert an edge into the adjacency list, maintaining lexicographical order
void insertEdge(Node* adjList[], char* from, char* to) {
    Node* newNode = (Node*)malloc(sizeof(Node));
    strcpy(newNode->airport, to);
    newNode->next = NULL;

    int index = (from[0] - 'A') * 26 * 26 + (from[1] - 'A') * 26 + (from[2] - 'A');

    if (adjList[index] == NULL || strcmp(adjList[index]->airport, to) > 0) {
        newNode->next = adjList[index];
        adjList[index] = newNode;
    } else {
        Node* current = adjList[index];
        while (current->next != NULL && strcmp(current->next->airport, to) < 0) {
            current = current->next;
        }
        newNode->next = current->next;
        current->next = newNode;
    }
}

// Iterative DFS using a stack to build the itinerary
void dfs(char* airport, Node* adjList[], char** itinerary, int* index) {
    char* stack[MAX_TICKETS + 1];
    int stackSize = 0;

    stack[stackSize++] = airport;

    while (stackSize > 0) {
        char* currentAirport = stack[stackSize - 1];
        int idx = (currentAirport[0] - 'A') * 26 * 26 + (currentAirport[1] - 'A') * 26 + (currentAirport[2] - 'A');

        if (adjList[idx] != NULL) {
            Node* nextNode = adjList[idx];
            stack[stackSize++] = nextNode->airport;
            adjList[idx] = nextNode->next;
            // Do not free nextNode here; defer the free operation until the end
        } else {
            itinerary[(*index)--] = stack[--stackSize];
        }
    }
}

// Function to find the itinerary from the list of tickets
char** findItinerary(char*** tickets, int ticketsSize, int* ticketsColSize, int* returnSize) {
    Node* adjList[MAX_AIRPORTS] = {NULL};

    // Populate the adjacency list with the tickets
    for (int i = 0; i < ticketsSize; i++) {
        insertEdge(adjList, tickets[i][0], tickets[i][1]);
    }

    char** itinerary = (char**)malloc((ticketsSize + 1) * sizeof(char*));
    int index = ticketsSize;
    dfs("JFK", adjList, itinerary, &index);

    // Freeing nodes after DFS traversal is complete
    for (int i = 0; i < MAX_AIRPORTS; i++) {
        Node* current = adjList[i];
        while (current) {
            Node* next = current->next;
            free(current->airport);
            free(current);
            current = next;
        }
    }

    *returnSize = ticketsSize + 1;
    return itinerary;
}
相关推荐
AbandonForce2 分钟前
C++11:列表初始化||右值和移动语义||引用折叠和完美转发||可变参数模板||lambda表达式||包装器(function bind)
开发语言·数据结构·c++·算法
khalil10207 分钟前
代码随想录算法训练营Day-50 图论02 | 99.岛屿数量-深搜、99.岛屿数量-广搜 、100.岛屿的最大面积
数据结构·c++·算法·leetcode·深度优先·图论
Brilliantwxx7 分钟前
【C++】模版进阶(特化+分离编译+非类型模版参数)
开发语言·数据结构·c++·算法
Black蜡笔小新8 分钟前
自动化AI算法训练服务器DLTM企业级AI模型工作站构筑企业AI自主可控新模式
人工智能·算法·自动化
bnmoel8 分钟前
数据结构深度剖析链表全集:结构实现、分类与底层原理全解析
c语言·数据结构·算法·链表·双向链表
坚果派·白晓明16 分钟前
【鸿蒙PC三方库移植适配框架解读系列】第六篇:关键注意事项与最佳实践
c语言·开发语言·c++·华为·harmonyos·开源鸿蒙
童先生18 分钟前
华为云、阿里云、AWS签名机制详解! AK/SK + HMAC-SHA256 签名鉴权!
算法·阿里云·华为云·云计算
承渊政道20 分钟前
【贪心算法】(经典实战应用解析(二):最⻓递增⼦序列、递增的三元⼦序列、最⻓连续递增序列、买卖股票的最佳时机、买卖股票的最佳时机II)
数据结构·c++·学习·算法·leetcode·贪心算法·哈希算法
li星野22 分钟前
动态规划十题通关:从爬楼梯到编辑距离(Python + C++)
c++·python·学习·算法·动态规划
披着假发的程序唐25 分钟前
STM32 H743 MPU的配置使用方法
linux·c语言·c++·驱动开发·stm32·单片机·mcu