LeetCode #126 Word Ladder II

WL_2.png
/**
* Abstract: Actually if we take the words in the list as nodes, by 
* applying the rule of transformation we get a graph such that 
* every edge maps to a legal transition between its
* two vertices. And the problem here becomes a graph's single-source
* shortest path problem, which, can be solved by BFS.
* Reference: Algorithms, 4ed, by Robert Sedgewick&Kevin Wayne
*/

/**
* The queue here is impled array-basedly. A linked list version
* is used in previous submissions and it works as well, which,
* as a advantage over the array-based version here, eliminates the
* need of calculating the qsize(and the somewhat awkward corner case
* handling for when qsize equaling zero by assigning it wordListSize
* + 1: if (qsize == 0) { qsize = wordListSize + 1; })
*/
typedef struct QueueStruct {
    int *items, head, tail;
}*Queue;

Queue QueueCreate(int capacity) {
    Queue queue = (Queue)malloc(sizeof(*queue));
    queue->items = (int*)malloc(capacity * sizeof(int));
    queue->tail = queue->head = 0;
    return queue;
}

void QueueEnqueue(Queue queue, int item) { queue->items[queue->head++] = item; }

int QueueDequeue(Queue queue) { return queue->items[queue->tail++]; }

bool QueueIsEmpty(Queue queue) { return queue->head == queue->tail; }

typedef struct PLNodeStrcut {
    int *path;
    int n;
    struct PLNodeStrcut *next;
}*PLNode;

PLNode PLNodeCreate(int *path, int n) {
    PLNode x = (PLNode)malloc(sizeof(*x));
    x->path = (int*)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) { x->path[i] = path[i]; }
    x->n = n;
    x->next = NULL;
    return x;
}

typedef struct PathListStrcut {
    PLNode head;
    int count;
}*PathList;

PathList PathListCreate() {
    PathList pl = (PathList)malloc(sizeof(*pl));
    pl->head = NULL;
    pl->count = 0;
    return pl;
}

void PathListAdd(PathList pl, int *path, int n) {
    PLNode head = PLNodeCreate(path, n);
    head->next = pl->head;
    pl->head = head;
    pl->count++;
}

int* PathListDelete(PathList pl, int *n) {
    PLNode head = pl->head;
    pl->head = head->next;
    pl->count--;
    int *path = head->path;
    *n = head->n;
    free(head);
    return path;
}

int PathListCount(PathList pl) { return pl->count; }

bool PathListIsEmpty(PathList pl) { return pl->count == 0; }

char** create_transformation_sequence(int *path, int n, char *beginWord, char **wordList) {
    char **ts = (char**)malloc(n * sizeof(*ts));
    ts[0] = beginWord;
    for (int i = 1; i < n; i++) { ts[i] = wordList[path[i] - 1]; }
    return ts;
}

int* calculate_edge_to(int **table, int n, int *tableSize, int source, int qsize) {
    int *edgeTo = (int*)malloc(n * sizeof(*edgeTo));
    bool *marked = (bool*)malloc(n * sizeof(*marked));
    for (int i = 0; i < n; i++) { marked[i] = false; }
    marked[source] = true;
    Queue queue = QueueCreate(qsize);
    QueueEnqueue(queue, source);
    do {
        int v = QueueDequeue(queue);
        int *adj = table[v];
        int adjn = tableSize[v];
        for (int i = 0; i < adjn; i++) {
            int w = adj[i];
            if (!marked[w]) {
                marked[w] = true;
                edgeTo[w] = v;
                QueueEnqueue(queue, w);
            }
        }
    } while (!QueueIsEmpty(queue));
    return edgeTo;
}

int shortest_path_length(int **table, int n, int *tableSize, int source, int target, int qsize, int *edgeTo) {
    int min = 0;
    for (int v = target; v != source; v = edgeTo[v]) { 
        if (v >= 0 && v < n) {
            min++; 
        } else {
            min = INT_MAX;
            break;
        }
    }
    
    return min == INT_MAX ? INT_MAX : min + 1;
}

/*
* We do three prunings here:
* 1) leave out the vertices that should not be taken(see footnote for
*    more info on the taken array here);
* 2) leave out the vertices that are already on the path(added previously
*    along the way of the dfs);
* 3) leave out the vertiecs that are NOT one step further torward the dst
*    vertex(the vertex corresponding to endWord).
* footnote: we take into consideration only such vertices that the 
*           sum of the distance from the source(the vertex 
*           corresponding to beginWord) and the distance to the 
*           destination vertex(the vertex corresponding to endWord)
*           equals the pre-calculated length of the shortest path.
*/
void dfs(int **table, int n, int *tableSize, bool *taken, int *dstToSrc, int v, int target, int spl/*shortest path length*/, int *path, int pi/*path index*/, bool *opf/*on path flags*/, PathList pathList) {
    if (!taken[v]) return;
    int *adj = table[v];
    for (int i = 0; i < tableSize[v]; i++) {
        int w = adj[i];
        if (!opf[w] && (dstToSrc[w] == dstToSrc[v] + 1)) {
            if (pi < spl) {
                path[pi] = w;
                opf[w] = true;
                if (w == target) { 
                    PathListAdd(pathList, path, spl);
                    opf[w] = false;
                } else {
                    if (pi + 1 < spl) { dfs(table, n, tableSize, taken, dstToSrc, w, target, spl, path, pi + 1, opf, pathList); }
                    opf[w] = false;
                }
            } else {
                break;
            }
        }
    }
}

/**
* checks if word differs from key by one&only one character
*/
bool diff(char *key, char *word) {
    size_t diff = 0, n = strlen(key), i = 0;
    while (i < n && diff <= 1) {
        if (key[i] != word[i]) { diff++; }
        i++;
    }
    return diff == 1;
}

char *** findLadders(char * beginWord, char * endWord, char ** wordList, int wordListSize, int* returnSize, int** returnColumnSizes) {
    bool *blackList = (bool*)malloc(wordListSize * sizeof(*blackList));
    for (int i = 0; i < wordListSize; i++) { blackList[i] = false; }
    bool notFound = true;
    int target = 0;
    for (int i = 0; i < wordListSize; i++) {
        if (strcmp(endWord, wordList[i]) == 0) {
            notFound = false;
            target = i + 1;
            break;
        }
        if (strcmp(beginWord, wordList[i]) == 0) { blackList[i] = true; }
    }

    if (notFound) { 
        *returnSize = 0;
        return NULL;
    }

    int **table = (int**)malloc((wordListSize + 1) * sizeof(*table));
    int *tableSize = (int*)malloc((wordListSize + 1) * sizeof(*tableSize));
    for (int i = 0; i <= wordListSize; i++) { 
        table[i] = (int*)malloc(wordListSize * sizeof(int)); 
        tableSize[i] = 0;
    }
    
    //Build table
    for (int i = 0; i < wordListSize; i++) {
        if (diff(beginWord, wordList[i])) { 
            table[0][tableSize[0]++] = i + 1;
            table[i + 1][tableSize[i + 1]++] = 0;
        } 
    }
    for (int i = 0; (i < wordListSize); i++) { if (!blackList[i]) { for (int j = 0; j < wordListSize; j++) { if ((j != i) && !blackList[j] && diff(wordList[i], wordList[j])) { table[i + 1][tableSize[i + 1]++] = j + 1; } } } }
    int qsize = 0;
    for (int i = 0; i <= wordListSize; i++) { qsize += tableSize[i]; }
    if (qsize == 0) { qsize = wordListSize + 1; }

    int *edgeToSrc = calculate_edge_to(table, wordListSize + 1, tableSize, 0, qsize);
    int min = shortest_path_length(table, wordListSize + 1, tableSize, 0, target, qsize, edgeToSrc);
    if (min == INT_MAX) {//not reachable from beginWord
        *returnSize = 0;
        return NULL;
    }
    int *edgeToDst = calculate_edge_to(table, wordListSize + 1, tableSize, target, qsize);
    bool *taken = (bool*)malloc(sizeof(*taken) * (wordListSize + 1));
    int *dstToSrc = (int*)malloc((wordListSize +1) * sizeof(*dstToSrc));
    for (int v = 0; v <= wordListSize; v++) { 
        int ls = shortest_path_length(table, wordListSize + 1, tableSize, 0, v, qsize, edgeToSrc);
        int ld = shortest_path_length(table, wordListSize + 1, tableSize, target, v, qsize, edgeToDst);
        if (ls == INT_MAX) { ls = 0; }
        if (ld == INT_MAX) { ld = 0; }
        taken[v] = (min + 1) == (ls + ld);
        dstToSrc[v] = ls;
    }

    bool *opf = (bool*)malloc((wordListSize + 1) * sizeof(*opf));
    opf[0] = true;
    for (int i = 1; i <= wordListSize; i++) { opf[i] = false; }
    PathList pathList = PathListCreate();
    int *path = (int*)malloc(min * sizeof(*path));
    path[0] = 0;
    dfs(table, wordListSize + 1, tableSize, taken, dstToSrc, 0, target, min, path, 1, opf, pathList);
    *returnSize = PathListCount(pathList);
    *returnColumnSizes = (int*)malloc(*returnSize * sizeof(int));
    for (int i = 0; i < *returnSize; i++) { (*returnColumnSizes)[i] = min; }
    char ***switches = (char***)malloc(PathListCount(pathList) * sizeof(*switches));
    int i = 0;
    while (!PathListIsEmpty(pathList)) {
        int n = 0;
        int *path = PathListDelete(pathList, &n);
        switches[i] = create_transformation_sequence(path, n, beginWord, wordList);
        i++;
    }
    return switches;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,265评论 6 490
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,078评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,852评论 0 347
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,408评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,445评论 5 384
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,772评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,921评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,688评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,130评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,467评论 2 325
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,617评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,276评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,882评论 3 312
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,740评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,967评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,315评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,486评论 2 348

推荐阅读更多精彩内容