Advertisement
HXXXXJ

骰子问题

Apr 11th, 2019
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.35 KB | None | 0 0
  1. func findDic(_ dics:[[Character]], _ str: String) -> [[Int]]{
  2.    
  3.     //生成一个 char 对 set of dic index的 dictionary
  4.     var map = [Character: Set<Int>]() // char - list of dic(index)
  5.     for (index, dic) in dics.enumerated(){
  6.         for char in dic{
  7.             map[char, default: Set<Int>()].insert(index)
  8.         }
  9.     }
  10.    
  11.     //对于每个位置开始dfs (start with 0)
  12.     let arr = Array(str)
  13.     var visited = Set<Int>()
  14.     var curr = [Int]()
  15.     var result = [[Int]]()
  16.     print(map)
  17.     dfs(map, &visited, arr, 0, &curr, &result)
  18.     return result
  19.    
  20. }
  21. func dfs(_ map: [Character: Set<Int>], _ visited: inout  Set<Int>, _ arr: [Character], _ start: Int, _ curr : inout [Int], _ result: inout [[Int]]){
  22.     if start == arr.count{
  23.         result.append(curr)
  24.         return
  25.     }
  26.     if let list = map[arr[start]]{
  27.         for index in list{
  28.             if !visited.contains(index) {
  29.                 visited.insert(index)
  30.                 curr.append(index)
  31.                 dfs(map, &visited, arr, start + 1, &curr, &result)
  32.                 curr.removeLast()
  33.                 visited.remove(index)
  34.             }
  35.         }
  36.     }
  37. }
  38.  
  39.  
  40. let dice : [Character] = ["A","B","A"]
  41. let dice2 : [Character] = ["B","B","B"]
  42. let dice3 : [Character] = ["C","D","A"]
  43.  
  44. let dices = [dice, dice2, dice3]
  45. print(findDic(dices, "ABC"))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement