On the coderbyte to do exercises swift programming ability, Youdao algorithm problem somewhat meaning, the topic is called "correct Path".
Analysis: The title is the matrix of the 5*5, the starting point is (0,0), the end point is (4,4), a total of 25 points. If you follow a two-dimensional array, the endpoint value should be equal to 24. Equivalent to-1 to the left, to the right equivalent to +1, up to-5, and to the right equivalent to +5. Because it is a 5*5 matrix, it is necessary to judge the boundary condition when moving. That is: move from the starting point to the right 4 times, move down 4 times to reach the end point; one left, one right, or one at a time is logically equivalent to not moving (PS: Not changing the threshold of 4 times).
Methods of Solving problems:
The first thought was recursion, which was simple and rough and poorly performing, and was thinking of other algorithms ...
Add character substitution feature 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 C Haracter = = "U" {if stepd < 4 {STEPD + = 1} else {return FAL SE}} return stepr==0 && stepd==0} func Correctpath (_ str:string)-> str ing {//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.REPL
Acefirst (Source: "?", Dest: "L")) Paths.append (Correctpath (Str.replacefirst (Source: "?", Dest: "R")) For p in paths {if isValidpath (str:p) {return p}}} Let path = Correctpath ("???
Rrurdr? ") Print (PATH)