forked from tinggo/algorithm011-class02
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 433.minimum-genetic-mutation.go
- Loading branch information
1 parent
cf701d6
commit 0adb48f
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
func minMutation(start string, end string, bank []string) int { | ||
bankMap := make(map[string]struct{}, len(bank)) | ||
for i := range bank { bankMap[bank[i]] = struct{}{} } | ||
|
||
if _, ok := bankMap[end]; !ok { return -1 } | ||
|
||
changeMap := map[byte][]byte{ | ||
'A': []byte{'C', 'G', 'T'}, | ||
'C': []byte{'A', 'G', 'T'}, | ||
'G': []byte{'A', 'C', 'T'}, | ||
'T': []byte{'A', 'C', 'G'}, | ||
} | ||
|
||
queue := []string{ start } | ||
step := 0 | ||
for len(queue) > 0 { | ||
n := len(queue) | ||
for i := 0; i < n; i++ { | ||
start = queue[0] | ||
queue = queue[1:] | ||
if start == end { return step } | ||
// 这里可以优化,只变更需要变更的字符;(最开始循环一遍字符串就知道哪些字符不一样,需要多少步) | ||
for j := 0; j < len(start); j++ { | ||
for _, c := range changeMap[start[j]] { | ||
arr := []byte(start) | ||
arr[j] = c | ||
tmp := string(arr) | ||
if _, ok := bankMap[tmp]; ok { | ||
queue = append(queue, tmp) | ||
} | ||
} | ||
} | ||
} | ||
step++ | ||
} | ||
return -1 | ||
} |