WEEK#10 Dynamic Programming_Freedom Trail

Description of the Problem

In the video game Fallout 4, the quest "Road to Freedom" requires players to reach a metal dial called the "Freedom Trail Ring", and use the dial to spell a specific keyword in order to open the door.
Given a string ring, which represents the code engraved on the outer ring and another string key, which represents the keyword needs to be spelled. You need to find the minimum number of steps in order to spell all the characters in the keyword.
Initially, the first character of the ring is aligned at 12:00 direction. You need to spell all the characters in the string key one by one by rotating the ring clockwise or anticlockwise to make each character of the string key aligned at 12:00 direction and then by pressing the center button. At the stage of rotating the ring to spell the key character key[i]: You can rotate the ring clockwise or anticlockwise one place, which counts as 1 step. The final purpose of the rotation is to align one of the string ring's characters at the 12:00 direction, where this character must equal to the character key[i].
If the character key[i] has been aligned at the 12:00 direction, you need to press the center button to spell, which also counts as 1 step. After the pressing, you could begin to spell the next character in the key (next stage), otherwise, you've finished all the spelling.

Example:

image.png

Input: ring = "godding", key = "gd"
Output: 4
Explanation:For the first key character 'g', since it is already in place, we just need 1 step to spell this character.For the second key character 'd', we need to rotate the ring "godding" anticlockwise by two steps to make it become "ddinggo".Also, we need 1 more step for spelling.So the final output is 4.

Note:
Length of both ring and key will be in range 1 to 100.
There are only lowercase letters in both strings and might be some duplicate characters in both strings.
It's guaranteed that string key could always be spelled by rotating the string ring.


Thinking Process

All letters in ring have a smallest cost to travel to another letter in ring.
So for a ring of size n, we construct a 2-d array M[n][n], in which M[i][j] means the smallest cost travel from ring[i] to ring[j].
In this way, what we need will be :

Pointer and Result are initialized as 0.
For i ∈ (0, key.length)
1. Find j, so that ring[j] = key[i];
2. Result += M[Pointer][j];
3. Pointer = j;

This method can only work out very limited test cases, for it is rather static than dynamic. It is unable to take all the moves into account, thus can't work out the best solution.
Every step that the algorithm takes could all have an influence on the result, yet this method can only choose the smallest cost at current step, overlooking that taking the smallest step now may result in a bigger cost later on.
For example, ring = "iotfo", key = "fioot"
When currently pointing to 'i', and wish to go to 'o', the cost of left-side 'o' and right-side 'o' are the same, but only by taking the right-side one can we get the best solution, cause its closer to 't' than the left-side one.

class Solution {
public:
    int findRotateSteps(string ring, string key) {
        int length = ring.size();
        vector<vector<int>> Matrix = construct(length);
        int result = 0, pointer = 0;
        for (int i = 0; i < key.length(); i++) {
            int findleft = 0, findright = 0;
            bool jflag = false;
            for (int j = pointer; j < length; j++) {
                if (ring[j] == key[i]) {
                    findright = j;
                    break;
                }
                if (j == length-1 && jflag == false) {
                    j = -1;
                    jflag = true;
                }
            }
            bool kflag = false;
            for (int k = pointer; k >= 0; k--) {
                if (ring[k] == key[i]) {
                    findleft = k;
                    break;
                }
                if (k == 0 && kflag == false) {
                    k = length;
                    kflag = true;
                }
            }
            int smaller = Matrix[pointer][findleft] <= Matrix[pointer][findright] ? Matrix[pointer][findleft] : Matrix[pointer][findright];
            result += smaller;
            if (Matrix[pointer][findleft] <= Matrix[pointer][findright])
                pointer = findleft;
            else
                pointer = findright;
        }
        return result;
    }

    vector<vector<int>> construct(int length) {
        vector<vector<int>> Matrix;
        Matrix.resize(length);
        for (int i = 0; i < length; i++)
            Matrix[i].resize(length);

        for (int i = 0; i < length; i++)
            Matrix[i][i] = 1;

        for (int i = 0; i < length; i++) {
            int count = 1;
            bool flag = false;
            for (int j = i + 1; j < length; j++) {
                if (flag == false)
                    Matrix[i][j] = ++count;
                if (count >= length / 2 + 1 && flag == false) {
                    flag = true;
                    continue;
                }
                if (flag) {
                    if (length % 2 == 1)
                        Matrix[i][j] = count--;
                    else
                        Matrix[i][j] = --count;
                }
            }
        }

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

推荐阅读更多精彩内容

  • 今天姐姐说她的小狗雪花记性越来越不好了,经常在外面转几圈才想起回家,视力不济,听力也不好,还胡乱小便。。。好像患上...
    悠然的桥阅读 454评论 0 7
  • 《作为意志和表象的世界》开篇第一句就是:“世界是我的表象”。在叔本华看来,整个世界首先是作为人类的印象而存在,对人...
    木卯丁阅读 173评论 0 0
  • 今天和朋友聊天,她说觉得我是幸运的,我也值得这份幸运。可是直到聊天结束,我都不解她口中的幸运,于我是什么。1 自小...
    晨creezy阅读 241评论 0 0