美文网首页
剑指 Offer 12. 矩阵中的路径

剑指 Offer 12. 矩阵中的路径

作者: 邦_ | 来源:发表于2022-03-14 09:17 被阅读0次
    
     func exist(_ board: [[Character]], _ word: String) -> Bool {
            
            let wordArray = Array(word)
            var tempArray = board
    
            for i in 0...tempArray.count - 1 {
                
                for j in 0...tempArray[0].count - 1 {
                    
                    if dfs(&tempArray, wordArray, i, j, 0) {
                        return true
                    }
                   
                }
                
                
            }
        
            
            
          return  false
        }
        
        
        func dfs(_ array: inout [[Character]],_ words:[Character],_ i:Int,_ j:Int,_ k: Int) -> Bool {
            
            if i >= array.count || j >= array[0].count || i < 0 || j < 0 || array[i][j] != words[k]{
                return false
            }
            if k == words.count - 1 {
                return true
            }
            
            array[i][j] = "\0"
            
            let res = dfs(&array, words, i + 1, j, k + 1) || dfs(&array, words, i - 1, j ,k + 1) || dfs(&array, words, i, j + 1, k + 1) || dfs(&array, words, i, j - 1, k + 1)
            
            array[i][j] = words[k]
    
            return res
            
        }
    
    
    
    
    
    
    

    相关文章

      网友评论

          本文标题:剑指 Offer 12. 矩阵中的路径

          本文链接:https://www.haomeiwen.com/subject/ptparrtx.html