Herzlich Willkommen

Live processing contents

Monday, January 31, 2011

Dijktra (simple MAPPING)

djiktra sample
*FILE    1.java
package model;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
import java.util.Vector;


public class Dijkstra
{
  public Integer[] getShortestPaths(WeightedGraph graph, int source)
  {
    int n = graph.size() + 1;

    Vector<Integer> vertices = new Vector<Integer>(n);
    Integer[] dist = new Integer[n];
    Integer[] previous = new Integer[n];
    initialization(n, vertices, dist, previous);
    dist[source] = Integer.valueOf(0);
    while (!vertices.isEmpty()) {
      Integer smallestVertex = getVertexWithSmallestDistance(vertices, dist);
      if (dist[smallestVertex.intValue()].intValue() == 99999999) break;
      vertices.remove(smallestVertex);
      Vector<Integer> neighbors = graph.neighbors(smallestVertex.intValue());
      for(Integer neighbor : neighbors){
        int alt = dist[smallestVertex.intValue()].intValue() + graph.getCost(smallestVertex.intValue(), neighbor.intValue());
        if (alt < dist[neighbor.intValue()].intValue()) {
          dist[neighbor.intValue()] = Integer.valueOf(alt);
          previous[neighbor.intValue()] = smallestVertex;
        }
      }
    }
    return previous;
  }

  private void initialization(int n, Vector<Integer> vertices, Integer[] dist, Integer[] previous) {
    for (int i = 0; i < n; i++) {
      vertices.add(Integer.valueOf(i));
      dist[i] = Integer.valueOf(99999999);
      previous[i] = null;
    }
  }

  private Integer getVertexWithSmallestDistance(Vector<Integer> vertices, Integer[] dist) {
    Integer smallestVertex = null;
    int smallestCost = 99999999;
    for (Integer vertex : vertices) {
      if (dist[vertex.intValue()].intValue() <= smallestCost) {
        smallestCost = dist[vertex.intValue()].intValue();
        smallestVertex = vertex;
      }
    }
    return smallestVertex;
  }
}

-------------------------------------------------------------------------------------------------------
ABSTRACT DATA TYPE (ADT)
*File 2.java
~~~~~~~~~~~~~~~~~~~~~~~~~~

package model;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;


public abstract class GraphADT
{
  public static final int INFINITY = 99999999;//jumlah infinity
  public final List<GraphListener> listeners = new ArrayList();//membuat sebuah list yang berisi actionlisteners
  protected boolean directed;//penanda apakah directed apa bukan
  protected boolean weighted;//untuk penanda wighted apa tidak
  protected int numVertices; //jumlah vertexnya
  protected boolean[][] adj;//untuk menetukan adjacent anatar vertex

  public abstract void addVertices(int number);//menambah vertex

  public abstract void addArc(int i, int j);//memberikan hubungan di vertex

  public void removeArc(int i, int j)//menghilangkan hubungan antar vertex
  {
    this.adj[i][j] = false;
  }

  public void addEdge(int i, int j) {//menambahkan edge ke 2 vertex
    addArc(i, j);
    addArc(j, i);

    for (GraphListener listener : this.listeners)//memberikan informasi ke interface bahwa sebuah edge di berikan
      listener.notifyEdgeAdded();
  }

  public abstract boolean isArc(int i, int j);//apakah terdapa hubungan antar vertex

  public boolean isEdge(int i, int j) {
    return (isArc(i, j)) && (isArc(j, i));//apakah ada edgenya di anatar dua vertex
  }
  public abstract Vector<Integer> neighbors(int x);//abstrack untuk adjacent

  public int getNumVertices() {//mendapatkan jumlah vertex
    return this.numVertices;
  }

  public abstract int size();//abstrac untuk ukuran

  public boolean isDirected() {
    return this.directed;//getter untuk directe atau bukan
  }

  protected static boolean[][] adj_allocate(int n) {//mengalokasikan adjacent
    return new boolean[n][n];
  }

  public boolean isWeighted() {//getter untuk weighted ato bukan
    return this.weighted;
  }

  public void notifyNewGraphCreated() {//memberitahuke listener kalau seuah graph baru di ciptakan
    for (GraphListener listener : this.listeners)
      listener.notifyNewGraphCreated();
  }

  public void notifyGraphChanged()//memberitahuke listener kalau seuah graph baru di ubah
  {
    for (GraphListener listener : this.listeners)
      listener.notifyGraphChanged();
  }

  public boolean[][] getAdj()//mendapatkan nilai adjacentnya
  {
    return this.adj;
  }
}
-------------------------------------------------------------------------------------------------------
FILE 3.Java
applet
~~~~~~~~~~~~~~~~~~~~~

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

/**
 *
 * @author aginta
*/
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

public class GraphApplet extends JApplet {

    private GraphDisplay display;

    public void init() {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {//membuat thread

                public void run() {
                    GraphApplet.this.initGUI();//mengeksekusi initgui untuk ditampilkan
                }
            });
        } catch (Exception e) {
        }

    }

    private void initGUI() {

        JButton buttonbaru = new JButton();
        buttonbaru.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                display.newGraph();
            }
        });
        buttonbaru.setText("Baru");

        JButton buttonExit = new JButton();
        buttonExit.setText("Exit");
        buttonExit.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });

        this.display = new GraphDisplay();

        JButton buttonTitik = new JButton();
        buttonTitik.setText("Buat Titik");
        buttonTitik.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                display.getGraph().addVertices(1);
            }
        });

        JButton buttonCari = new JButton();
        buttonCari.setText("Cari Jalan");
        buttonCari.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                display.setShortestPath(display.dijkstraShortestPath());
            }
        });

        setLayout(new BorderLayout());
        JPanel panelTombol = new JPanel();
        panelTombol.add(buttonbaru);
        panelTombol.add(buttonTitik);
        panelTombol.add(buttonCari);
        panelTombol.add(buttonExit);
        add(panelTombol,BorderLayout.NORTH);
        add(display);
        setSize(new Dimension(600, 400));
    }
}
------------------------------------------------------------------------------------------------------------
FILE 4.Java
Display Graph
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

/**
 *
 * @author aginta
 */
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class GraphDisplay extends JPanel
        implements GraphListener, MouseListener, MouseMotionListener {

    private List<Vertex> vertices;
    private boolean movingVertex;
    private boolean drawingLine;
    private int[] shortestPath;
    private GraphADT graph;

    public GraphDisplay()//konstruktor
    {
        //this.app = app;
        this.vertices = new ArrayList();

        addMouseListener(this);
        addMouseMotionListener(this);
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        GraphADT graph = this.getGraph();
        if (graph == null) {
            return;
        }
        for (Vertex v : this.vertices) {
            paintVertex(g, v);
            Vector neighbors = graph.neighbors(v.getNumber());
            g.setColor(Color.BLACK);
            for (Iterator localIterator2 = neighbors.iterator(); localIterator2.hasNext();) {
                int neighbor = ((Integer) localIterator2.next()).intValue();
                paintArrow(g, graph, v, (Vertex) this.vertices.get(neighbor));
            }
        }
    }

    private void paintVertex(Graphics g, Vertex v) {
        Point point = v.getPoint();
        int x = (int) point.getX();
        int y = (int) point.getY();
        if (v.isSelected()) {
            g.setColor(Color.BLUE);
        } else {
            g.setColor(Color.RED);
        }
        g.fillOval(x, y, 15, 15);
        if (v.isSelected()) {
            g.setColor(Color.BLUE);
        } else {
            g.setColor(Color.RED);
        }
        g.drawString(String.valueOf(v.getNumber()), x, y);
    }

    public void paintArrow(Graphics g, GraphADT graph, Vertex source, Vertex target) {
        Point s = source.getPoint();
        Point t = target.getPoint();
        int sx = (int) s.getX();
        int tx = (int) t.getX();
        int sy = (int) s.getY();
        int ty = (int) t.getY();

        if (this.shortestPath != null) {
            if ((graph.isDirected()) && (isArcOnPath(source.getNumber(), target.getNumber()))) {
                g.setColor(Color.GREEN);
            } else if (isEdgeOnPath(source.getNumber(), target.getNumber())) {
                g.setColor(Color.GREEN);
            }
        } else {
            g.setColor(Color.BLACK);
        }

        g.drawLine(sx + 10, sy + 5, tx + 10, ty + 5);

        if (graph.isDirected()) {
            paintArrow(g, sx + 10, sy + 5, tx + 10, ty + 5);
        }
        if (graph.isWeighted()) {
            int cost = ((WeightedGraph) graph).getCost(source.getNumber(), target.getNumber());
            String weight = "[" + cost + "]";
            Font font = g.getFont();
            g.setFont(new Font("DialogInput", 1, 12));
            g.setColor(Color.BLACK);
            g.drawString(weight, (sx + tx) / 2, (sy + ty) / 2 + 22);
            g.setFont(font);
        }
    }

    private void paintArrow(Graphics g, int x0, int y0, int x1, int y1) {
        int deltaX = x1 - x0;
        int deltaY = y1 - y0;
        double frac = 0.05D;

        g.drawLine(x0, y0, x1, y1);
        g.drawLine(x0 + (int) ((1.0D - frac) * deltaX + frac * deltaY), y0
                + (int) ((1.0D - frac) * deltaY - frac * deltaX), x1, y1);
        g.drawLine(x0 + (int) ((1.0D - frac) * deltaX - frac * deltaY), y0
                + (int) ((1.0D - frac) * deltaY + frac * deltaX), x1, y1);
    }

    private boolean isArcOnPath(int source, int target) {
        for (int i = 0; i < this.shortestPath.length - 1; i++) {
            if ((this.shortestPath[i] == source) && (this.shortestPath[(i + 1)] == target)) {
                return true;
            }
        }
        return false;
    }

    private boolean isEdgeOnPath(int source, int target) {
        for (int i = 0; i < this.shortestPath.length - 1; i++) {
            if ((this.shortestPath[i] == source) && (this.shortestPath[(i + 1)] == target)) {
                return true;
            }
            if ((this.shortestPath[i] == target) && (this.shortestPath[(i + 1)] == source)) {
                return true;
            }
        }

        return false;
    }

    public void notifyVertexAdded(int n) {
        if (n > 1) {
            for (int i = 0; i < n; i++) {
                Vertex vtx = new Vertex();
                vtx.setNumber(i);
                Random random = new Random();
                int xMax = (int) getSize().getWidth();
                int yMax = (int) getSize().getHeight();
                int randomX = random.nextInt(xMax - i * 5);
                int randomY = random.nextInt(yMax - i * 5);
                vtx.setPoint(new Point(randomX, randomY));
                this.vertices.add(vtx);
            }
            setCircularPaintingStrategy();
            repaint();
        } else {
            Vertex vtx = new Vertex();
            vtx.setNumber(this.getGraph().getNumVertices() - 1);
            vtx.setPoint(new Point(100, 100));
            this.vertices.add(vtx);

            setSelectedVertex(vtx);
            this.movingVertex = true;
        }
    }

    public void setCircularPaintingStrategy() {
        int n = graph.getNumVertices();

        int radius = (int) getSize().getWidth() / 4;
        int xOffset = 2 * radius;
        int yOffSet = (int) getSize().getHeight() / 2;
        double alfa = 0.0D;

        for (int v = 0; v < n; v++) {
            alfa += 6.283185307179586D / n;
            double x = 1.75D * radius * Math.cos(alfa) + xOffset;
            double y = radius * Math.sin(alfa) + yOffSet;
            ((Vertex) this.vertices.get(v)).setPoint(new Point((int) x, (int) y));
        }
        repaint();
    }

    public void notifyEdgeAdded() {
        updateUI();
    }

    public void notifyNewGraphCreated() {
        this.vertices = new ArrayList();
        repaint();
    }

    public void notifyGraphChanged() {
        repaint();
    }

    public boolean isMovingVertex() {
        return this.movingVertex;
    }

    public void setMovingVertex(boolean movingVertex) {
        this.movingVertex = movingVertex;
    }

    public List<Vertex> getVertices() {
        return this.vertices;
    }

    public void setVertices(List<Vertex> vertices) {
        this.vertices = vertices;
        repaint();
    }

    public Vertex getSelectedVertex() {
        for (Vertex v : this.vertices) {
            if (v.isSelected()) {
                return v;
            }
        }
        return null;
    }

    public void setSelectedVertex(Vertex v) {
        if (((getSelectedVertex() != null) && (getSelectedVertex().isSelected())) || ((getSelectedVertex() != null) && (getSelectedVertex().isSelected()))) {
            getSelectedVertex().setSelected(false);
        }
        if (v != null) {
            v.setSelected(true);
        }
        repaint();
    }

    public boolean isDrawingLine() {
        return this.drawingLine;
    }

    public void setDrawingLine(boolean drawingLine) {
        this.drawingLine = drawingLine;
    }

    public int[] getShortestPath() {
        return this.shortestPath;
    }

    public void setShortestPath(int[] shortestPath) {
        this.shortestPath = shortestPath;
        repaint();
    }

    public void mouseClicked(MouseEvent event) {
        boolean vertexClicked = vertexClicked(event);
        if (vertexClicked) {
            if (!this.isMovingVertex()) {
                this.setMovingVertex(true);
            }
        } else {
            this.setSelectedVertex(null);
            this.setMovingVertex(false);
        }
        if (this.getShortestPath() != null) {
            this.setShortestPath(null);
        }
    }

    public void mousePressed(MouseEvent event) {
        vertexClicked(event);
    }

    public void mouseReleased(MouseEvent event) {
        //GraphADT graph = this.getApp().getGraph();
        if (this.isDrawingLine()) {
            Vertex source = this.getSelectedVertex();
            vertexClicked(event);
            Vertex target = this.getSelectedVertex();
            connect(graph, source, target);
            this.setDrawingLine(false);
        }
    }

    private void connect(GraphADT graph, Vertex source, Vertex target) {
        if (target != null) {
            int i = source.getNumber();
            int j = target.getNumber();
            if (!graph.isWeighted()) {
                if (graph.isDirected()) {
                    graph.addArc(i, j);
                } else {
                    graph.addEdge(i, j);
                }
            } else {
                String k = "";
                try {
                    k = JOptionPane.showInputDialog(null, "Isi Jarak :?");
                } catch (NumberFormatException e) {
                }

                int cost = Integer.parseInt(k);
                if (graph.isDirected()) {
                    ((WeightedGraph) graph).addArc(i, j, cost);
                } else {
                    ((WeightedGraph) graph).addEdge(i, j, cost);
                }
            }
        }
    }

    public void mouseEntered(MouseEvent event) {
    }

    public void mouseExited(MouseEvent event) {
    }

    public void mouseDragged(MouseEvent event) {
        Vertex selectedVertex = this.getSelectedVertex();
        if ((selectedVertex != null)
                && (!this.isDrawingLine())) {
            this.setDrawingLine(true);
        }

        if (this.isDrawingLine()) {
            Vertex source = this.getSelectedVertex();
            if (source != null) {
                drawLine(event, source);
            }
        }
    }

    private void drawLine(MouseEvent event, Vertex source) {
        Point p1 = source.getPoint();
        int x1 = (int) p1.getX() + 5;
        int y1 = (int) p1.getY() + 5;
        Point p2 = event.getPoint();
        int x2 = (int) p2.getX() + 5;
        int y2 = (int) p2.getY() + 5;
        this.getGraphics().drawLine(x1, y1, x2, y2);
        this.repaint();
    }

    public void mouseMoved(MouseEvent event) {
        if ((this.isMovingVertex()) && (this.getSelectedVertex() != null)) {
            Vertex v = this.getSelectedVertex();
            v.setPoint(event.getPoint());
            this.updateUI();
        }
    }

    private boolean vertexClicked(MouseEvent event) {
        Point click = event.getPoint();
        int click_x = (int) click.getX();
        int click_y = (int) click.getY();
        boolean vertexClicked = false;
        Vertex clicked = null;
        for (Vertex v : this.getVertices()) {
            Point p = v.getPoint();
            int x = (int) p.getX() + 8;
            int y = (int) p.getY() + 8;
            if ((Math.abs(click_x - x) < 8) && (Math.abs(click_y - y) < 8)) {
                vertexClicked = true;
                clicked = v;
            }
        }
        this.setSelectedVertex(clicked);
        return vertexClicked;
    }

    private Integer[] getShortestPaths(WeightedGraph graph, int source) {
        return new Dijkstra().getShortestPaths(graph, source);
    }//mendapatkan nilai dan jalur dari wighted graph, dan asal..dan memanggil class Dijkstra dan method getsortes path

    public int[] dijkstraShortestPath() {//method untuk mendapatkan inputan dari user
        int n = this.getGraph().getNumVertices();//mendapatkan jumlah vertex melalui class aplication sbg penghubungnya
        int source;//menyimpan asal hasil input user
        int target;//menyimpan tujuan hasil input user
        String A = "";
        String B = "";
        try {
            A = JOptionPane.showInputDialog(null, "Dari ?");//message input dialog
            source = Integer.parseInt(A);
        } catch (NumberFormatException e) {

            return null;
        }

        if ((source < 0) || (source > n)) {
            JOptionPane.showMessageDialog(null, "Asal salah");
        }
        try {
            B = JOptionPane.showInputDialog(null, "Tujuan : ?");
            target = Integer.parseInt(B);
        } catch (NumberFormatException e) {

            return null;
        }

        if ((target < 0) || (target > n)) {
            JOptionPane.showMessageDialog(null, "Tujuan salah");
        }

        Integer[] previous = getShortestPaths((WeightedGraph) this.getGraph(), source);//mendapatkan nilai masing2 jalur
        int max = getGraph().getNumVertices();//mendapatkan jumlah vertex
        int[] path = new int[max];//menyimpan langkah di edge
        Integer pointer = Integer.valueOf(target);//mendapatkan index target
        for (int i = 0; i < max; i++) {//perulangan untuk menetukan jalur yang paling kecil antar vertex dari tujuan
            path[i] = pointer.intValue();//index jalur dengan nilai terendah dari perhitungan akan masuk sebagai jalurnya
            if (previous[pointer.intValue()] == null) {//ketika nilai pointer sudah null karena tidak ada adjacent vertex lagi
                break;//maka berhenti dan berarti sudah sampai ke asal
            }
            pointer = previous[pointer.intValue()];//nilai pointer di ubah ke nilai akhir yaitu awalnya
        }
        return reverse(path);//membalik jalur yg awal dari tujuan ke asal menjadi asala ke tujuan
    }

    public int[] reverse(int[] b) {//method membalik path
        int left = 0;//menetukan nilai kanan dan kiri untuk membalik
        int right = b.length - 1;
        while (left < right) {//selama kiri < kanan maka akan terus loping
            int temp = b[left];//nilai b di kiri disimpan sementara di temp
            b[left] = b[right];//nilai kiri di ubah menjadi nilai kanan
            b[right] = temp;//kanan di ubah menjadi kiri
            left++;
            right--;
        }
        return b;
    }

    public void newGraph() {//konstruktor
        this.setVertices(new ArrayList());//menyimpan vertex2 ke dalam sebuah arraylist baru
        this.graph = new WeightedGraph(false);//set weighted ke posisi defaul seebelum di set
        this.setShortestPath(null);//set jalur ke kosong

        this.graph.listeners.add(this);//tambahkan listener untuk event
    }

    public GraphADT getGraph() {//mendapatkan semua method dari graphADT untuk digunakan lewat claass ini
        return this.graph;
    }

    public void setGraph(GraphADT graph) {//method untuk menempatkan event listener
        this.graph = graph;
        graph.listeners.add(this);
        graph.notifyGraphChanged();
    }
}
------------------------------------------------------------------------------------------------------------
FILE 5.Java
Listener
~~~~~~~~~~~~~~~~~~~~~~
package model;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



/**
 *
 * @author aginta
*/
public abstract interface GraphListener
{
  public abstract void notifyVertexAdded(int paramInt);

  public abstract void notifyEdgeAdded();

  public abstract void notifyNewGraphCreated();

  public abstract void notifyGraphChanged();
}
---------------------------------------------------------------------------------------------------------------
FILE  6.Java
MAIN
~~~~~~~~~~~~~~~~~~~~~~~~
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JFrame;

/**
 *
 * @aginta
*/
public class Utama {
    public static void main(String[] args){
        JFrame Frametampil =new JFrame("Dijkstra");
        Container konApplet =Frametampil.getContentPane();
        GraphApplet ObjApplet =new GraphApplet();
        ObjApplet.init();
        Frametampil.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Frametampil.setSize(600, 500);
        Frametampil.setLocation(200,100);
        konApplet.add(ObjApplet,BorderLayout.CENTER);
        Frametampil.setVisible(true);

    }
}
------------------------------------------------------------------------------------------------------------
FILE 7.Java
vertex
~~~~~~~~~~~~~~
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package model;

/**
 *
 * @author aginta
*/
import java.awt.Point;

public class Vertex
{
  private int number;//sebagai index
  private Point point;//menyimpan koordinat dari vertex
  private boolean selected;//penanda di pilih atau tidak

  public Vertex()
  {
  }

  public Vertex(int number)//konstruktor dengan argumen jumlah titik
  {
    this.number = number;
  }

  public int getNumber() {
    return this.number;//mendapatkan jumlah vertex
  }

  public void setNumber(int number) {//menset jumlah vertex
    this.number = number;
  }

  public Point getPoint() {
    return this.point;//mendapatkan koordinat vertex
  }

  public void setPoint(Point point) {
    this.point = point;//set koordinat titik
  }

  public boolean isSelected() {
    return this.selected;//menset di pilih atau tidak
  }

  public void setSelected(boolean selected) {
    this.selected = selected;//menset apakah di pilih atau tidak
  }
}
--------------------------------------------------------------------------------------------------------------
FILE 8.Java
weighted Graph
~~~~~~~~~~~~~~~~~~~~~
package model;

import java.util.Vector;


public class WeightedGraph extends GraphADT
{
  private int[][] costs;

  public WeightedGraph(boolean directed)//konstruktor untuk
  {
    this.numVertices = 0;
    this.weighted = true;
    this.directed = directed;
  }

  public WeightedGraph(GraphADT graph) {
    this(false);
    int n = graph.getNumVertices();
    if (n > 0) {
      addVertices(n);
    }
    for (int i = 0; i < n; i++)
      for (int j = i; j < n; j++) {
        if ((i == j) || (
          (graph.getAdj()[i][j] == false) && (graph.getAdj()[j][i] == false))) continue;
        addEdge(i, j, getCost(i, j));
      }
  }

  private static int[][] costs_allocate(int n)
  {
    int[][] costs = new int[n][n];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        if (i != j) {
          costs[i][j] = 99999999;
        }
      }
    }
    return costs;
  }

  public void addVertices(int n) {
    boolean[][] matrix = adj_allocate(this.numVertices + n);
    for (int i = 0; i < this.numVertices; i++) {
      System.arraycopy(this.adj[i], 0, matrix[i], 0, this.numVertices);
    }
    this.adj = matrix;

    int[][] costsMatrix = costs_allocate(this.numVertices + n);

    for (int i = 0; i < this.numVertices; i++) {
      System.arraycopy(this.costs[i], 0, costsMatrix[i], 0, this.numVertices);
    }
    this.costs = costsMatrix;

    this.numVertices += n;

    for (GraphListener listener : this.listeners)
      listener.notifyVertexAdded(n);
  }

  public void addArc(int i, int j, int cost)
  {
    this.costs[i][j] = cost;
    addArc(i, j);
  }

  public void addArc(int i, int j) {
    this.adj[i][j] = true;
    for (GraphListener listener : this.listeners)
      listener.notifyEdgeAdded();
  }

  public void addEdge(int i, int j, int cost)
  {
    this.costs[i][j] = cost;
    this.costs[j][i] = cost;

    addEdge(i, j);
  }

  public boolean isArc(int i, int j) {
    return this.adj[i][j];
  }

  public Vector<Integer> neighbors(int i) {
    Vector nbrs = new Vector();
    for (int j = 0; j < this.numVertices; j++) {
      if ((j == i) ||
        (this.adj[i][j] == false)) continue;
      nbrs.addElement(Integer.valueOf(j));
    }

    return nbrs;
  }

  public int size() {
    int sz = 0;
    for (int i = 0; i < this.numVertices; i++) {
      for (int j = 0; j < this.numVertices; j++) {
        if (this.adj[i][j] != false) {
          sz++;
        }
        if (this.adj[i][j] != this.adj[j][i])
          this.directed = true;
      }
    }
    return !this.directed ? sz / 2 : sz;
  }

  public void setCost(int i, int j, int val) {
    this.costs[i][j] = val;
  }

  public int getCost(int i, int j) {
    return this.costs[i][j];
  }
}
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------
separate all JAVA Classes in each way (rename it as you want : XXX.java)
just run it


AGINTA GENIUSA
--------------------------------------------------------------------------------------------------------------
2010

No comments:

Post a Comment