Exemplo n.º 1
0
func NewDijkstra(g *Graph, s int) *Dijkstra {
	this := &Dijkstra{}

	this.edgeTo = make([]Edge, g.V())
	this.distTo = make([]algorithms.Double, g.V())

	for v := 0; v < g.V(); v++ {
		this.distTo[v] = algorithms.Double(math.Inf(1))
	}
	this.distTo[s] = 0.0

	if NewCycle(g).HasCycle() {
		this.cycle = true
		this.pq = container.NewMinPriorityQueue(g.V())
		this.pq.Push(&container.PriorityQueueItem{s, algorithms.Double(0.0)})

		for !this.pq.IsEmpty() {
			pqi := this.pq.Pop().Value.(*container.PriorityQueueItem)
			this.relax(g, pqi.Index)
		}
	} else {
		this.cycle = false
		iter := NewDFO(g).ReversePost().Iterator()
		for iter.HasNext() {
			v := iter.Next().Value.(int)
			this.relax(g, v)
		}
	}

	return this
}
Exemplo n.º 2
0
func NewGraphFromReader(r io.Reader, gt GraphType) *Graph {
	var v, e, w int
	var err error
	var this *Graph

	scanner := bufio.NewScanner(r)
	scanner.Split(bufio.ScanWords)

	scanner.Scan()
	if v, err = strconv.Atoi(scanner.Text()); err != nil {
		fmt.Printf(err.Error())
		return nil
	}

	switch gt {
	case DIGRAPH:
		this = NewDigraph(v)
	case EWDIGRAPH:
		this = NewEWDigraph(v)
	default:
		this = NewUnigraph(v)
	}

	scanner.Scan()
	if e, err = strconv.Atoi(scanner.Text()); err != nil {
		fmt.Printf(err.Error())
		return nil
	}

	for i := 0; i < e; i++ {
		scanner.Scan()
		if v, err = strconv.Atoi(scanner.Text()); err != nil {
			fmt.Printf(err.Error())
			return nil
		}
		scanner.Scan()
		if w, err = strconv.Atoi(scanner.Text()); err != nil {
			fmt.Printf(err.Error())
			return nil
		}
		if gt == EWDIGRAPH {
			var weight float64
			scanner.Scan()
			if weight, err = strconv.ParseFloat(scanner.Text(), 64); err != nil {
				fmt.Printf(err.Error())
				return nil
			}
			this.AddWeightedEdge(v, w, algorithms.Double(weight))
		} else {
			this.AddEdge(v, w)
		}
	}
	return this
}
Exemplo n.º 3
0
func (this *Dijkstra) HasPathTo(v int) bool {
	return this.distTo[v] < algorithms.Double(math.Inf(1))
}