0% found this document useful (0 votes)
31 views

Coding Nomor 4 UAS THE Struktur Data

This document contains code for implementing a breadth-first search (BFS) algorithm in Java. It defines a Graph class with methods to add edges between vertices and perform a BFS starting from a given source vertex, outputting each visited vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

Coding Nomor 4 UAS THE Struktur Data

This document contains code for implementing a breadth-first search (BFS) algorithm in Java. It defines a Graph class with methods to add edges between vertices and perform a BFS starting from a given source vertex, outputting each visited vertex.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

import java.io.

*;

import java.util.*;

class Main

private int V;

private LinkedList<Integer> adj [];

Main (int v)

V = v;

adj = new LinkedList[v];

for (int i=0; i<v; ++i)

adj[i] = new LinkedList ();

void addEdge (int v, int w)

adj[v].add(w);

void BFS (int s)

boolean visited[] = new boolean [V];

LinkedList<Integer> queue = new LinkedList<Integer>();

visited[s] = true;

queue.add(s);

while (queue.size() !=0)


{

s = queue.poll();

System.out.print (s+" ");

Iterator<Integer> i = adj[s].listIterator();

while (i.hasNext())

int n = i.next();

if (!visited[n])

visited[n] = true;

queue.add(n);

public static void main (String arg[])

Graph g = new Graph (4);

g.addEdge(0,0);

g.addEdge(0,2);

g.addEdge(1,0);

g.addEdge(1,3);

g.addEdge(2,1);

g.addEdge(3,2);

System.out.println("BFS dengan vertex awal 1");


g.BFS(1);

You might also like