题解 | #基因变异最小次数#
基因变异最小次数
https://www.nowcoder.com/practice/ca6b659a3fde42c59276c9db98febd94
package main
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param start string字符串
* @param end string字符串
* @param bank string字符串一维数组
* @return int整型
*/
func minMutation( start string , end string , bank []string ) int {
// write code here
queue :=[]string{start}
visited :=make(map[string]bool)
visited[start]=true
step :=0
for len(queue)>0{
size :=len(queue)
for i:=0;i<size;i++{
curr :=queue[0]
queue=queue[1:]
if curr==end{
return step
}
for _,gene :=range bank{
if !visited[gene]&&isOneMutationAway(curr,gene){
queue = append(queue, gene)
visited[gene]=true
}
}
}
step++
}
return -1
}
func isOneMutationAway(curr,gene string)bool{
count :=0
for i:=0;i<8;i++{
if curr[i]!=gene[i]{
count++
}
}
return count==1
}
查看7道真题和解析
爱玛科技公司福利 17人发布