Correct Path解题方法

来源:互联网 发布:seo外包顾问服务 编辑:程序博客网 时间:2024/05/16 10:56

     在CoderByte上做题练习Swift编程能力, 有道算法题有点意思, 题目叫“Correct Path”。


分析: 题目是5*5的矩阵, 起点是(0,0),  终点是(4,4), 总共25个点。 如果按照二维数组理解, 终点值应该等于24。向左等价于-1, 向右等价于+1,向上等价于-5,向右等价于+5。因为是5*5的矩阵,移动时要判断边界条件。 即:从起点开始向右移动4次,向下移动4次才能到达终点; 一左一右或者一上一下在逻辑上相当于没动(PS:不改变4次的门限值)。


解题方法:

      最先想到的是递归, 简单粗暴且性能很差; 正在想其它算法中......

//添加字符替换功能extension String {    func replaceFirst(source: String, dest: String) -> String {        let index = self.index(of: "?")        if index == nil {            return self        }                var result = ""        for i in 0..<self.count {            if i == index!.encodedOffset {                result.append(dest)            } else {                result.append((self as NSString).substring(with: NSMakeRange(i, 1)))            }        }                return result    }}func isValidPath(str: String) -> Bool {    var stepR = 4    var stepD = 4        for character in str {        if character == "l" {            if stepR < 4 {                stepR += 1            } else {                return false            }        }        if character == "r" {            if stepR > 0 {                stepR -= 1            } else {                return false            }        }        if character == "d" {            if stepD > 0 {                stepD -= 1            } else {                return false            }        }        if character == "u" {            if stepD < 4 {                stepD += 1            } else {                return false            }        }    }        return stepR==0 && stepD==0}func CorrectPath(_ str: String) -> String {        // code goes here    // Note: feel free to modify the return type of this function    if !str.contains("?") {        return str    }        for character in str {        if character == "?" {            var paths: [String] = []            paths.append(CorrectPath(str.replaceFirst(source: "?", dest: "d")))            paths.append(CorrectPath(str.replaceFirst(source: "?", dest: "u")))            paths.append(CorrectPath(str.replaceFirst(source: "?", dest: "l")))            paths.append(CorrectPath(str.replaceFirst(source: "?", dest: "r")))                        for p in paths {                if isValidPath(str: p) {                    return p                }            }        }    }        return ""    }let path = CorrectPath("???rrurdr?")print(path)


  


阅读全文
0 0