: ๋ฃจํธ ๋
ธ๋(ํน์ ๋ค๋ฅธ ์์์ ๋
ธ๋)์์ ์์ํด์ ์ธ์ ํ ๋
ธ๋๋ฅผ ๋จผ์ ํ์ํ๋ ๋ฐฉ๋ฒ ( ์ฆ, ๊น๊ฒ(deep) ํ์ํ๊ธฐ ์ ์ ๋๊ฒ(wide) ํ์)
๋ ๋
ธ๋ ์ฌ์ด์ ์ต๋จ ๊ฒฝ๋ก ํน์ ์์์ ๊ฒฝ๋ก๋ฅผ ์ฐพ๊ณ ์ถ์ ๋ ์ด ๋ฐฉ๋ฒ์ ์ ํํ๋ค.
public class BFSGraph {
private int V; // ๋
ธ๋์ ๊ฐ์
private LinkedList<Integer> adj[]; // ์ธ์ ๋ฆฌ์คํธ
/* ์์ฑ์ */
public BFSGraph(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);
}
/* s๋ฅผ ์์ ๋
ธ๋๋ก ํ BFS๋ก ํ์ํ๋ฉด์ ํ์ํ ๋
ธ๋๋ค์ ์ถ๋ ฅ */
void BFS(int s) {
// ๋
ธ๋์ ๋ฐฉ๋ฌธ ์ฌ๋ถ๋ฅผ ํ๋จ
boolean visited[] = new boolean[V];
// BFS ๊ตฌํ์ ์ํ ํ (Queue) ์์ฑ
LinkedList<Integer> queue = new LinkedList<Integer>();
// ํ์ฌ ๋
ธ๋๋ฅผ ๋ฐฉ๋ฌธํ ๊ฒ์ ํ์ ์ฝ์
(enqueue)
visited[s] = true;
queue.add(s);
// ๋ชจ๋๊ฐ ์ถ๋ ฅ ํ ๋๊น์ง Queue๋ฅผ ๋ฐ๋ณต
while (queue.size() != 0) {
// ๋ฐฉ๋ฌธํ ๋
ธ๋๋ฅผ ํ์์ ์ถ์ถ(dequeue)ํ๊ณ ๊ฐ์ ์ถ๋ ฅ
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[] args) {
BFSGraph g = new BFSGraph(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
System.out.println("vertax 2์์ ์์ํ๋ BFS(๋๋น ์ฐ์ ํ์)");
g.BFS(2); /* ์ฃผ์ด์ง ๋
ธ๋๋ฅผ ์์ ๋
ธ๋๋ก BFS ํ์ */
// 2 0 3 1
}
}