【发布时间】:2017-04-13 14:43:20
【问题描述】:
我一直在学习围棋,我正在用它做一个 BFS 拼图。我决定的队列实现是:
//define the queue for our BFS algo as frontier.
type frontier struct {
queue []*graphNode
}
func (F *frontier) buildFrontier() {
F.queue = make([]*graphNode, 0, 1000)
}
func (F *frontier) pop() (g *graphNode) {
if F.isEmpty() {
panic("pop on empty queue!")
}
temp := F.queue[0]
F.queue = F.queue[1:]
return temp
}
func (F *frontier) push(g *graphNode) {
F.queue = append(F.queue, g)
}
func (F *frontier) isEmpty() bool {
return len(F.queue) == 0
}
我有两个问题:
这是一个好的实现吗? go 中关于队列的文档很少,通常有一些关于向量的旧帖子,并且列表似乎有太多开销(这对我来说并不重要,但我正在尝试以最好的方式做到这一点) .
为什么对对象(在本例中为结构指针 F *frontier)的调用必须是指针?似乎语法的工作方式应该是指针的默认值,而不是显式的(即为什么你不想在这些实例中使用指针?)
修改后的循环版本:
//define the queue for our BFS algo as frontier.
type frontier struct {
queue []*graphNode
size, head, capacity int
}
func (F *frontier) buildFrontier() {
F.capacity = 1
F.queue = make([]*graphNode, F.capacity)
F.size = 0
F.head = 0
}
func (F *frontier) pop() (g *graphNode) {
if F.isEmpty() {
panic("pop on empty queue!")
}
F.size = (F.size - 1)
temp := F.queue[F.head]
F.head = (F.head + 1) % F.capacity
return temp
}
func (F *frontier) push(g *graphNode) {
if F.isFull() {
newSlice := make([]*graphNode, F.capacity*2)
copy(newSlice, F.queue)
F.queue = newSlice
F.capacity *= 2
}
F.queue[(F.head+F.size)%F.capacity] = g
F.size = (F.size + 1)
}
func (F *frontier) isEmpty() bool {
return F.size == 0
}
func (F *frontier) isFull() bool {
return F.size == F.capacity
}
【问题讨论】: