41
Ứng dụng thuật toán Dijkstra trong Shortest Path Routing

Giai Thuat Dijkstra Cho Sortest Path Routing

Embed Size (px)

Citation preview

Page 1: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Page 2: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

PHẦN 2:

TRÌNH BÀY ĐỀ TÀI NGHIÊN CỨU

ỨNG DỤNG THUẬT TOÁN DIJKSTRA TRONG SHORTEST PATH ROUTING

Mô tả đề tài và vấn đề liên quanĐịnh tuyến trong mạng thông tin:

Định tuyến (routing):

Định tuyến là quá trình chọn lựa các đường đi trên một mạng máy tính để gửi

dữ liệu qua đó. Việc định tuyến được thực hiện cho nhiều loại mạng, trong đó có mạng

điện thoại, liên mạng, Internet, mạng giao thông.

Định tuyến chỉ ra hướng, sự di chuyển của các gói (dữ liệu) được đánh địa chỉ

từ mạng nguồn của chúng, hướng đến đích cuối thông qua các node trung gian. Thiết bị

phần cứng chuyên dùng được gọi là router (bộ định tuyến). Tiến trình định tuyến

thường chỉ hướng đi dựa vào bảng định tuyến, đó là bảng chứa những lộ trình tốt nhất

đến các đích khác nhau trên mạng. Vì vậy việc xây dựng bảng định tuyến, được tổ chức

trong bộ nhớ của router, trở nên vô cùng quan trọng cho việc định tuyến hiệu quả.

Routing khác với bridging (bắc cầu) ở chỗ trong nhiệm vụ của nó thì các cấu

trúc địa chỉ gợi nên sự gần gũi của các địa chỉ tương tự trong mạng, qua đó cho phép

nhập liệu một bảng định tuyến đơn để mô tả lộ trình đến một nhóm các địa chỉ. Vì thế,

routing làm việc tốt hơn bridging trong những mạng lớn, và nó trở thành dạng chiếm ưu

thế của việc tìm đường trên mạng internet.

Các lớp thuật toán định tuyến:

Thuật toán vector (distance-vector routing protocol):

Thuật toán này dùng thuật toán Bellman-Ford. Nó chỉ định một con số, gọi là

chi phí (hay trọng số), cho mỗi một liên kết giữa các node trong mạng. Các node sẽ gửi

thông tin từ điểm A đến điểm B qua đường đi mang lại tổng chi phí thấp nhất (là tổng

các chi phí của các kết nối giữa các node được dùng).

Thuật toán hoạt động với những hành động đơn giản. Khi một node khởi động

lần đầu, nó chỉ biết các node kề trực tiếp với nó, và chi phí trực tiếp để đi đến đó (thông

tin, danh sách của các đích, tổng chi phí của từng node, và bước kế tiếp để gửi dữ liệu

Page 3: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

đến đó tạo nên bảng định tuyến, hay bảng khoảng cách). Mỗi node, trong một tiến

trình, gửi đến từng “hàng xóm” tổng chi phí của nó để đi đến các đích mà nó biết. Các

node “hàng xóm” phân tích thông tin này, và so sánh với những thông tin mà chúng

đang “biết”; bất kì điều gì cải thiện được những thông tin chúng đang có sẽ được đưa

vào các bảng định tuyến. Đến khi kết thúc, tất cả các node trên mạng sẽ tìm ra bước

truyền kế tiếp tối ưu đến tất cả mọi đích, và tổng chi phí tốt nhất.

Thuật toán trạng thái kết nối (Link-state routing protocols):

Khi áp dụng các thuật toán trạng thái kết nối, mỗi node sử dụng cơ sở dữ liệu

của nó như là một bản đồ của mạng với dạng đồ thị. Để làm để làm điều này, mỗi node

phát đi tới tổng thể mạng những thông tin về các node khác mà nó có thể kết nối được,

và từng node góp thông tin một cách độc lập vào bản đồ. Sử dụng bản đồ này, mỗi

router sau đó sẽ quyết định về tuyến đường tốt nhất từ nó đến mọi node khác.

Các router sẽ trao đổi gói tin LSA với những router khác. Đây là những gói tin

nhỏ, chứa thông tin về các router. Mỗi router sẽ dựa vào LSAs này để tạo ra topological

database, sử dụng giải thuật SPF (Short Path First) để tìm ra đường đi. Mỗi router đều

xác định được chính xác topology của mạng. Chính vì vậy router sẽ đưa ra quyết định

để đưa packet đến đích tốt hơn. Mỗi router trong mạng sẽ báo cáo trạng thái của nó, các

link nối trực tiếp và trạng thái của mỗi link. Router sẽ nhân bản thông tin này tới tất cả

các router trên mạng. Cuối cùng tất cả các router trên mạng đều có cái nhìn giống nhau

về topology mạng.

Thuật toán làm theo cách này là thuật toán Dijkstra (thuật toán mà ta sẽ tìm hiểu

và ứng dụng), bằng cách xây dựng cấu trúc dữ liệu khác, dạng cây, trng đó node hiện

tại là gốc, và chứa mọi node khác trong mạng. Bắt đầu với một cây ban đầu chỉ chứa

chính nó. Sau đó lần lượt từ tập các node chưa được thêm vào cây, nó sẽ thêm node có

chi phí thấp nhất để đến một node đã có trên cây. Tiếp tục quá trình đến khi mọi node

đều được thêm. Cây này sau đó phục vụ để xây dựng bảng định tuyến, đưa ra bước

truyền kế tiếp tối ưu,… để từ một node đến bất kì node khác trên mạng.

Thuật toán định tuyến bằng trạng thái kết nối phản ứng nhanh nhạy hơn, và

trong một khoảng thời gian có hạn, đối với sự thay đổi kết nối. Ngoài ra, những gói

được gửi qua mạng trong định tuyến bằng trạng thái kết nối thì nhỏ hơn những gói

dùng trong định tuyến bằng vector.

Page 4: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Giao thức định tuyến:Giao thức định tuyến được dùng trong khi thi hành thuật toán định tuyến để

thuận tiện cho việc trao đổi thông tin giữa các mạng, cho phép các router xây dựng

bảng định tuyến một cách linh hoạt. Trong một số trường hợp, giao thức định tuyến có

thể tự chạy đè lên giao thức đã được định tuyến.

Danh sách các giao thức định tuyến:

Giao thức định tuyến trong:

Router Information Protocol (RIP).

Open Shortest Path First (OSPF).

Intermediate System to Intermediate System (IS-IS).

Interior Gateway Routing Protocol (IGRP) (thuộc sở hữu của Cisco).

Enhanced IGRP (EIGRP) (thuộc sở hữu của Cisco).

Giao thức định tuyến ngoài:

Exterior Gateway Protocol (EGP).

Border Gateway Protocol (BGP).

Constrained Shortest Path First (CSPF).

Lý thuyết Graph:Một Graph G, được định nghĩa bởi tập các đỉnh V và tập hợp các cạnh E. Các

đỉnh thường được gọi là các nút (node) và chúng biểu diễn vị trí (ví dụ một điểm chứa

lưu lượng hoặc một khu vực chứa thiết bị truyền thông). Các cạnh được gọi là các liên

kết và chúng diễn biến phương tiện truyền thông. Graph có thể được biểu diễn như sau:

G=(V,E)

Page 5: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Hình 1.Một Graph đơn giản.

Mặc dù theo lý thuyết, V có thể là tập hợp rỗng hoặc không có xác định nhưng

thông thường V là tập hợp xác định khác rỗng, nghĩa là có thể biểu diễn

V={v |i=1,2,…,N}

Trong đó N là số lượng nút. Tương tự E được biểu diễn :

E={e |i=1,2,…,M}

Một liên kết, e tương ứng với một kết nối giữa một cặp nút. Có thể biểu diễn

liên kết e giữa nút i và k bởi :

e=(v,v) hoặc e=(i,k).

Một liên kết gọi là đi tới một nút nếu đó là một trong hai điểm cuối của liên kết.

Nút i và k gọi là kề nhau nếu tồn tại một liên kết (i,k) giữa chúng. Những nút như vậy

được xem là các nút “hàng xóm”. Bậc của nút là số lượng liên kết đi tới nút hya là số

lượng nút hàng xóm.

Một liên kết có thể có hai hướng. Khi đó thứ tự của các nút là không có ý nghĩa.

Ngược lại thứ tự các nút có ý nghĩa. Trong trường hợp thứ tự các nút có ý nghĩa, một

liên kết có thể được xem như là một cung và được định nghĩa :

a=[v,v] hoặc a=[i,k].

k được gọi là cận kề hướng ra đối với i nếu một cung [i,k] tồn tại và bậc hướng

ra của i là số lượng các cung như vậy.

Một graph goi là một mạng nếu các liên kết và các nút có mặt trong liên kết có

các thuộc tính (chẳng hạn như độ dài, dung lượng, loại,…). Các mạng được sử dụng để

mô hình các vấn đề cần quan tâm trong truyền thông, các thuộc tính riêng biệt của các

nút và liên kết thì liên quan đến các vấn đề cụ thể trong truyền thông.

Page 6: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Một graph có các liên kết gọi là graph vô hướng, tuy nhiên một graph vô

hướng, tuy nhiên một graph có các cung gọi là graph hữu hướng. Một graph hữu hướng

có thể có cả các liên kết vô hướng. Thông thường, các graph được giả sử là vô hướng,

hoặc sự phân biệt đó là không có ý nghĩa.

Có thể có khả năng xảy ra hiện tượng xuất hiện nhiều hơn một liên kết giữa

cùng một cặp nút. Những liên kết như vậy gọi là các liên kết song song. Một graph có

liên kết song song gọi là một multigraph.

Cũng có khả năng xuất hiện các liên kết giữa một nút nào đó và chính nút đó.

Những liên kết đó được gọi là các self loop. Một graph không có các liên kết song song

hoặc các self loop gọi là một graph đơn giản.

Lý thuyết nghiên cứuĐịnh tuyến đường dẫn ngắn nhất (Shortest Path Routing):

Bài toán tìm đường đi ngắn nhất là một bài toán khá quan trọng trong quá trình

thiết kế và phân tích mạng. Hầu hết các bài toán định tuyến có thể giải quyết như giải

quyết bài toán tìm đường đi ngắn nhất khi một “độ dài” thích hợp được gắn vào mỗi

cạnh (hoặc cung) trong mạng. Trong khi các thuật toán thiết kế thì cố gắng tìm kiếm

cách tạo ra các mạng thỏa mãn tiêu chẩn độ dài đường đi.

Bài toán đơn giản nhất của loại toán này là tìm đường đi ngắn nhất giữa hai nút

cho trước. Loại bài toán này có thể là bài toán tìm đường đi ngắn nhất từ một nút tới tất

cả các nút còn lại, tương đương bài toán tìm đường đi ngắn nhất từ tất cả các điểm đến

một điểm. Đôi khi đòi hỏi phải tìm đường đi ngắn nhất giữa tất cả các cặp nút.

Ta xét các graph hữu hướng và giả sử rằng đã biết độ dài của một cung giữa

mỗi cặp nút i và j là l. Các độ dài này không cần phải đối xứng. Khi một cung không

tồn tại thì độ dài l được giả sử là rất lớn (chẳng hạn lớn gấp n lần độ dài cung lớn nhất

trong mạng). Chú ý rằng có thể áp dụng quá trình này cho các mạng vô hướng bằng

cách thay mỗi cạnh bằng hai cung có cùng độ dài. Ban đầu giả sử rằng l là dương hoàn

toàn; sau đó giả thiết này có thể được thay đổi.

Phần lớn các mạng chuyển mạch gói sử dụng các thuật toán khác nhau của

phương pháp chọn tuyến đường ngắn nhất do lớp mạng thực hiện. Một số mạng chọn

tuyến theo cách thức tập trung, thiết lập đường dẫn giữa nút nguồn và nút đích ở trung

tâm điều hành mạng NMC (Network Management Center) hay trung tâm điều khiển

Page 7: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

chọn tuyến RCC (Routing Control Center) rồi sau đó phân phối các thông tin chọn

tuyến đến tất cả các nút chuyển mạch trong mạng. Các nút mạng khác sử dụng cách

thức phi tập trung hay còn gọi là cách thức phân bố, từng nút trao đổi thông tin chọn

tuyến và giá thành với các nút khác trong mạng trên cơ sở tương tác cho đến khi các

bảng định tuyến đáp ứng được yêu cầu định tuyến ngắn nhất.

Thuật toán Dijkstra:Tất cả các thuật toán tìm đường đi ngắn nhất đều dựa vào việc lồng nhau giữa

các đường đi ngắn nhất nghĩa là một nút k thuộc một đường đi ngắn nhất từ i tới j thì

đường đi ngắn nhất từ i tới j sẽ bằng đường đi ngắn nhất từ i tới k kết hợp với đường đi

ngắn nhất từ j tới k. Vì thế chúng ta có thể tìm đường đi ngắn nhất bằng công thức đệ

quy sau:

d = (d + d)

Hình 2. Các đường đi ngắn nhất lồng nhau.

Dxy là độ dài của đường đi ngắn nhất từ x tới y. Khó khăn của cách tiếp cận

này là phải có một cách khởi động đệ quy nào đó vì chúng ta không thể khởi động với

các giá trị bất kỳ ở vế phải của phương trình trên.

Thuật toán Dijkstra phù hợp cho việc tìm đường đi ngắn nhất từ một nút i tới tất

cả các nút khác. Bắt đầu bằng cách thiết lập

d = 0 và d = ∞ ∀ i ≠ j

Sau đó thiết lập

d ← l ∀ j là nút kề cận của i

Sau đó tìm nút j có d là bé nhất. Tiếp đó lấy chính nút j vừa chọn để khai triển

các khoảng cách các nút khác, nghĩa là bằng cách thiết lập

d ← min(d, d + l)

Tai môi giai đoan cua qua trinh, gia tri cua d la gia tri ươc lương hiên co cua

đương đi ngăn nhât tư i tơi k, va thưc ra la đô dai đương đi ngăn nhât đa đươc tim cho

tơi thơi điêm đo. Xem d như la nhan trên nut k. Qua trinh sư dung môt nut đê triên khai

cac nhan cho cac nut khac goi la qua trinh quet nut.

Page 8: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Thưc hiên tương tư, tiêp tuc tim cac nut chưa đươc quet co nhan be nhât va

quet no. Chu y răng, vi gia thiêt tât ca cac l đêu dương do đo môt nut không thê gan cho

nut khac môt nhan be hơn chinh nhan cua nut đo. Vi vây, khi môt nut đươc quet thi viêc

quet lai no nhât thiêt không bao giơ xay ra. Nêu nhan trên môt nut thay đôi, nut đo phai

đươc quet lai.

Vi du : xet mang như hinh sau, trên môi đương ghep nôi co cac trong sô tương

ưng vơi gia thanh cua tưng đương, đê đơn gian ta coi cac trong sô nay theo ca hai chiêu

la như nhau, măc du trên thưc tê chung co thê khac nhau vê gia tri. Đê chon đươc

đương dân ngăn nhât tư môt nguôn tơi tât ca cac nut trong mang, đoi hoi phai co kiên

thưc vê câu hinh tông thê cua mang (danh sach cac nut va cac ghep nôi giưa chung)

cung như gia thanh cua tưng đương nôi. Điêu đo dân tơi viêc tinh toan tâp trung dưa

trên thông tin đây đu lưu trong cac cơ sơ dư liêu trung tâm (Central Database).

Hinh 3. Vi du môt mang.

Thuât toan đươc thưc hiên theo tưng bươc, xây dưng mô hinh cây đương ngăn

nhât (Shortest Path Tree) co gôc tai nut nguôn (nut 1). Cac đương dân ngăn nhât tơi k

nut khac đươc tinh toan trong k bươc, chung đươc tâp hơp lai trong tâp N.

Coi D(v) la khoang cach (tông cua cac trong sô đương nôi doc theo đương dân)

tư nut nguôn 1 tơi nut v. Coi l(i,j) la gia thanh đa cho giưa 2 nut i va j. Thuât toan gôm

2 bươc:

1.Bươc khơi đâu

Page 9: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Đăt N={1} (tâp N ban đâu chi gôm duy nhât 1 nut), vơi môi nut v ∉ N đăt

D(v)=l(l,v), vơi cac nut không nôi trưc tiêp vơi nut l ta coi gia thanh băng ∞ .

2.Bươc lăp

Tim nut w không thuôc N sao cho D(w) la tôi thiêu va bô sung w vao tâp N. Sau

đo thay D(v) cho toan bô cac nut không thuôc N con lai băng cach tinh:

D(v) ← min[D(v),D(w) + l(w,v)]

Bươc nay đươc lặp lai cho đên khi tât ca cac nut đêu co trong N.

Sau khi thưc hiên, ta lân lươt co đươc cac bươc mô ta bơi bang thông kê sau:

Bươc Tâp N D(2) D(3) D(4) D(5) D(6)

0 {1} 2 ∞ ∞ ∞ 5

1 {1,2} 2 3 ∞ ∞ 3

2 {1,2,3} 2 3 4 5 3

3 {1,2,3,6} 2 3 4 5 3

4 {1,2,3,6,4} 2 3 4 5 3

5 {1,2,3,6,4,5} 2 3 4 5 3

Mô hinh cây đương đi ngăn nhât nêu lây nut 1 lam nut nguôn co thê mô ta như

hinh ve sau:

Hinh 4.Mô hinh đương dân ngăn nhât.

Page 10: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Đich Nut tiêp theo

2 2

3 3

4 4

5 5

6 3

Hinh 5.Bang chon tuyên cho nut 1.

Vơi thuât toan nay ta co thê tinh đươc cac tuyên đương co đương dân ngăn nhât

cho tưng nut, cu thê ta coi nut đo la nut nguôn rôi thưc hiên cac bươc giai thuât kê trên.

Trong trương hơp chon tuyên theo phương thưc tâp trung, NMC se gưi cac bang chon

tuyên cho tưng nut môt sau khi đa thiêt lâp xong, con nêu mang sư dung phương thưc

phân bô thi tưng nut phai tinh lây bang đinh tuyên, cung sư dung cac thông tin tông thê

như trên (đươc cung câp bơi cac nut lân cân hoăc bơi NMC) va chon ra cây đương dân

cho riêng no.

Xây dựng và thiết kế chương trình minh họa thuật toán DijkstraXây dưng c hương trinh cơ bản tim đương đi ngăn nhât băng thuât toan Dijkstra:

Viêt băng ngôn nưa C:

#include<stdio.h>#include<conio.h>#include<math.h>#define filein “Dijkstra.inp”#define fileout “Dijkstra.out”#define NMAX 100#define MAX 1000int n,s,t;int c[NMAX][NMAX];int Previous[NMAX];bool Free[NMAX];int d[NMAX];

void Input_data(){ int i,j; FILE *fp; fp=fopen(filein,”r”);

Page 11: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

fscanf(fp,”%d%d%d”,&n,&s,&t); for(i=1;i<=n;i++){ for(j=1;j<=n;j++){ fscanf(fp,”%d”,&c[i][j]); if(c[i][j]==0) c[i][j]=MAX; } } fclose(fp); }

void Init(){ int v; for(v=1;v<=n;v++){ d[v]=c[s][v]; //Khơi tao gia tri đâu minpath tư s đên v la v=c[s][v] //Đanh dâu Previous[v]=s; //Tât ca cac đinh đêu ơ trang thai tư do Free[v]=true; } //cô đinh s Previous[s]=0; d[s]=0; Free[s]=false; }

void Dijkstra(){ int u,v,minp; //thưc hiên trong khi t con tư do While(Free[t]){ minp=MAX; //Tim trong tâp T ra đinh u co d[u] min. Chu y T la tâp hơp cac đinh chưa //co đinh nhan for(v=1;v<=n;v++){ if(Free[v]&&(minp>d[v])){ minp=d[v]; u=v; } } //Sau khi tim đươc đinh u thi ta cô đinh đinh u Free[u]=false; //Dung đinh u đê tôi ưu hoa cac đinh trong T if(Free[t]){ for( v=1;v<=n;v++){ if(Free[v]&&(d[u]+c[u][v]<d[v])){ //Sưa lai nhan cua v d[v]=d[u]+c[u][v]; //Lưu vêt Previous[v]=u; } }

Page 12: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

} } }

Void Output_data(){ Int i; FILE *fp; fp=fopen(fileout,”w”); fprintf(fp,”+Duong di ngan nhat tu %d den %d la: \n”,s,t); fprintf(fp,”%d<=”,t); i=Previous[t]; while(i!=s){ fprintf(fp,”%d<=”,i); i=Previous[i]; } fprintf(fp,”%d”,s); fprintf(fp,”\n+Do dai duong di ngan nhat la: %d”,d[t]); fclose(fp); }

Thiết kế phần mềm minh họa thuật toán Dijkstra:Sử dụng bộ công cụ Eclipse lập trình với Java.

Class Options:

Class Options chứa các Button để thực hiện việc vẽ các đỉnh, các cạnh (chi phí),

sửa, xóa, chạy thực thi thuật toán Dijkstra.

package Dijkstra3;

import java.awt.Button;import java.awt.Event;import java.awt.GridLayout;import java.awt.Panel;

class Options extends Panel {/** * */private static final long serialVersionUID = 1L;// Dat cac Options ben trai man hinh ung dung

Button b1 = new Button("Clear"); Button b2 = new Button("Run"); Button b3 = new Button("Step"); Button b4 = new Button("Reset"); Button b5 = new Button("Example"); Button b6 = new Button("Exit"); Button b7 = new Button("About"); GraphAlgorithm parent; boolean Locked=false;

Page 13: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Options(GraphAlgorithm myparent) {parent = myparent;setLayout(new GridLayout(7, 1, 0, 10));add(b1);add(b2);add(b3);add(b4);add(b5);add(b7);add(b6);

}

public boolean action(Event evt, Object arg) { if (evt.target instanceof Button) {

//Neu la JButton "Step" va Unlock thi thuc hien buoc dau tien va hien thi "Nextstep" len JButton, //nguoc lai thi khong thuc hien if (((String)arg).equals("Step")) { if (!Locked) { b3.setLabel("Next step"); parent.graphcanvas.stepalg(); } else parent.documentation.doctext.showline("locked"); } //Neu la JButton "Nextstep" thi thuc hien buoc tiep thep if (((String)arg).equals("Next step")){ parent.graphcanvas.nextstep(); } //Neu la JButton "Reset" thi thuc hien reset if (((String)arg).equals("Reset")) { parent.graphcanvas.reset(); b3.setLabel("Step"); parent.documentation.doctext.showline("all items"); } //Neu la JButton "Clear" thi xoa graphics if (((String)arg).equals("Clear")) { parent.graphcanvas.clear(); b3.setLabel("Step"); parent.documentation.doctext.showline("all items"); } //Neu la JButton "Run" va Unlock thi thuc hien tung buoc mac dinh //nguoc lai thi khong thuc hien if (((String)arg).equals("Run")) { if (!Locked) parent.graphcanvas.runalg(); else parent.documentation.doctext.showline("locked"); } //Neu la JButton "Example" va Unlock thi thuc hien default graphics //nguoc lai thi khong thuc hien if (((String)arg).equals("Example")) { if (!Locked)

Page 14: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

parent.graphcanvas.showexample(); else parent.documentation.doctext.showline("locked"); } //Neu la JButton "About" thi hien thi dialog About if(((String)arg).equals("About")){ dialog dig = new dialog(); } //Neu la JButton "Exit" thi thoat khoi chuong trinh if (((String)arg).equals("Exit")) { System.exit(0); } } return true; } public void lock() {

Locked=true; }

public void unlock() {Locked=false;b3.setLabel("Step");

} }

Class Documentation:

Class Documentation chứa document hướng dẫn sử dụng chương trình và các

chỉ dẫn cùng với việc minh họa chi phí giữa các đỉnh trong quá trình chạy thực hiện

giải thuật Dijkstra.

package Dijkstra3;

import java.awt.BorderLayout;import java.awt.Choice;import java.awt.Event;import java.awt.GridLayout;import java.awt.Label;import java.awt.Panel;import java.awt.TextArea;

class Documentation extends Panel {// Documentaion huong dan o phia tren man hinh ung dung

DocOptions docopt = new DocOptions(this); DocText doctext = new DocText();

Documentation() {setLayout(new BorderLayout(10, 10));add("West", docopt);add("Center", doctext);

}

Page 15: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

}

class DocOptions extends Panel {//Tao Choice huong dan ben trai man hinh ung dung

Choice doc = new Choice(); Documentation parent; DocOptions(Documentation myparent) {

setLayout(new GridLayout(2, 1, 5, 0));parent = myparent;add(new Label("DOCUMENTATION:"));doc.addItem("draw nodes");doc.addItem("remove nodes"); doc.addItem("move nodes");doc.addItem("the startnode");doc.addItem("draw arrows"); doc.addItem("change weights");doc.addItem("remove arrows");doc.addItem("clear / reset"); doc.addItem("run algorithm");doc.addItem("step through");doc.addItem("example");doc.addItem("about");doc.addItem("exit"); doc.addItem("all items");add(doc);

} public boolean action(Event evt, Object arg) { //Ham xu ly Choice if (evt.target instanceof Choice) {

String str=new String(doc.getSelectedItem()); parent.doctext.showline(str);

} return true; }}

class DocText extends TextArea {//TextDocumentation huong dan cho cac Choice va JButton

final String drawnodes = new String("DRAWING NODES:\n"+ "Draw a node by clicking the mouse on the screen

application.\n\n"); final String rmvnodes = new String("REMOVE NODES:\n"+

"To remove a node press <ctrl> and click on the node.\n"+ "You can not remove the startnode.\n"+ "Select another startnode, then you can remove the node.\n\n");

final String mvnodes = new String("MOVING NODES\n"+

"To move a node press <Shift>, click on the node,\nand drag it to"+

" its new position.\n\n"); final String startnode = new String("STARTNODE:\n"+

"The startnode is blue, other nodes are grey.\n"+

Page 16: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

"The first node you draw on the screen will be the startnode.\n"+ "To select another startnode press <ctrl>, click on the

startnode,\n"+ "and drag the mouse to another node.\n"+ "To delete the startnode, first select another startnode, and

then"+ "\nremove the node the usual way.\n\n");

final String drawarrows = new String("DRAWING ARROWS:\n"+

"To draw an arrow click mouse in a node,"+ "and drag it to another node.\n\n");

final String weight = new String("CHANGING WEIGHTS:\n"+

"To change the weight of an arrow, click on the arrowhead and drag\n"+

"it along the arrow.\n\n"); final String rmvarrows = new String("REMOVE ARROWS:\n"+

"To remove an arrow, change its weight to 0.\n\n"); final String clrreset = new String("<CLEAR> BUTTON: "+

"Remove the current graph from the screen.\n"+ "<RESET> BUTTON: "+ "Remove the results of the algorithm from the graph,\n"+ " and unlock screen.\n\n");

final String runalg = new String("<RUN> BUTTON: "+

"Run the algorithm on the graph, there will be a time\n" + "delay of +/- 1 second between steps.\n"+ "To run the algorithm slower, use <STEP>.\n");

final String step = new String("<STEP> BUTTON: " +

"An opportunity to step through the algorithm.\n"); final String example = new String("<EXAMPLE> BUTTON: "+

"Displays a default graph on the screen for you.\n"+ "You can then use <STEP> or <RUN>\n");

final String exitbutton = new String("<EXIT> BUTTON: " +

"Only works if applet is run with appletviewer.\n"); final String aboutbutton = new String("<ABOUT> BUTTON: " + "Show about Dijkstra program information.\n"); final String toclose = new String("ERROR: "+

"This position is to close to another node/arrow.\n"); final String done = new String("Algorithm has finished, " +

"follow green arrows from startnode to any node "+ "to get\nthe shortest path to " + "the node. The length of the path is written in the node.\n" +

"press <RESET> to reset the graph, and unlock the screen."); final String some = new String("Algorithm has finished, " +

"follow green arrows from startnode to any node "+ "to get\nthe shortest path to " + "the node. The length of the path is written in the node.\n" +

"There are no paths from the startnode to any gray node.\n" + "press <RESET> to reset the graph, and unlock the screen.");

Page 17: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

final String none = new String("Algorithm has finished, " +

"there are no nodes reachable from the start node.\n"+ "press <RESET> to reset the graph, and unlock the screen.");

final String maxnodes = new String("ERROR: "+

"Maximum number of nodes reached!\n\n"); final String info = new String("DOCUMENTATION:\n"+

"You can scroll through the documentation or get documentation\n"+ "on a specific "+ "item by selecting the item on the left.\nSelecting <All items> "+ "brings you back "+ " to the scrolling text.\n\n");

final String locked = new String("ERROR: "+

"Keyboard/mouse locked for this action.\n"+ "Either press <NEXT STEP> or <RESET>.\n");

final String doc = info + drawnodes + rmvnodes + mvnodes + startnode + drawarrows + weight + rmvarrows + clrreset + runalg + step + example + aboutbutton +

exitbutton;

DocText() {super(5, 2);setEditable(false);setText(doc);

} public void showline(String str) {

if (str.equals("draw nodes")) setText(drawnodes);else if (str.equals("remove nodes")) setText(rmvnodes);else if (str.equals("move nodes")) setText(mvnodes);else if (str.equals("the startnode")) setText(startnode);else if (str.equals("draw arrows")) setText(drawarrows);else if (str.equals("change weights")) setText(weight);else if (str.equals("remove arrows")) setText(rmvarrows);else if (str.equals("clear / reset")) setText(clrreset);else if (str.equals("run algorithm")) setText(runalg);else if (str.equals("step through")) setText(step);else if (str.equals("example")) setText(example);

else if (str.equals("exit")) setText(exitbutton); else if (str.equals("about")) setText(aboutbutton);

else if (str.equals("all items")) setText(doc);else if (str.equals("toclose")) setText(toclose); else if (str.equals("done")) setText(done); else if (str.equals("locked")) setText(locked);else if (str.equals("maxnodes")) setText(maxnodes);

else if (str.equals("none")) setText(none); else if (str.equals("some")) setText(some);

else setText(str); }}

Class dialog:

Page 18: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Class dialog chưa thông tin về phần mềm, người viết.

package Dijkstra3;

import java.awt.*;import java.awt.Component;import java.awt.GridBagConstraints;import java.awt.GridBagLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

import javax.swing.ImageIcon;import javax.swing.JButton;import javax.swing.JDialog;import javax.swing.JLabel;import javax.swing.JPanel;

class dialog extends JDialog implements ActionListener{

//tao Button OKJButton jb=new JButton("OK");

//tao JPanelJPanel jp1=new JPanel();JPanel jp2=new JPanel(new GridLayout(3,1));JPanel jp3=new JPanel();

ImageIcon img=new ImageIcon(this.getClass().getResource("/nhanntv/nhanntv1.png"));

//tao JLabelJLabel jlb1=new JLabel(img);JLabel jlb2=new JLabel("************Program Java to************");JLabel jlb3=new JLabel("****Dijkstra Algorithm Program Demo****");JLabel jlb4=new JLabel("***CopyWrite @2011 Edit by Nhanntv***");

//Tao LayoutGridBagLayout gb=new GridBagLayout();GridBagConstraints gbc=new GridBagConstraints();private static final long serialVersionUID = 1L;

public dialog(){setSize(300,200);setLayout(gb);jp1.add(jlb1);jp2.add(jlb2);jp2.add(jlb3);jp2.add(jlb4);jb.addActionListener(this);jp3.add(jb);gbc.fill=GridBagConstraints.EAST;addComponent(jp1,0,0,4,10);gbc.fill=GridBagConstraints.NORTHWEST;addComponent(jp2,0,10,3,15);gbc.fill=GridBagConstraints.NORTHWEST;addComponent(jp3,3,15,1,5);

Page 19: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

this.setVisible(true);}

@Overridepublic void actionPerformed(ActionEvent e) {

// TODO Auto-generated method stubif(e.getSource()==jb){

this.dispose();}

}

public void addComponent(Component c,int row,int col,int nrow,int ncol){

gbc.gridy=row;// toa do ygbc.gridx=col;// toa do xgbc.gridheight=nrow;// so dong chiemgbc.gridwidth=ncol;// so cot chiemgb.setConstraints(c,gbc);add(c);

}}

Class GraphCanvas:

Class GraphCanvas là Class đồ họa của chương trình, chứa các thuật toán giải

quyết việc tìm đường đi ngắn nhất trong mạng (Shortest Path Routing), các phương

thức để vẽ một mạng, xây dựng và tìm đường, đưa ra kết quả dưới dạng đồ họa cho

giải thuật Dijkstra.

package Dijkstra3;

import java.awt.Canvas;import java.awt.Color;import java.awt.Dimension;import java.awt.Event;import java.awt.Font;import java.awt.FontMetrics;import java.awt.Graphics;import java.awt.Image;import java.awt.Point;

class GraphCanvas extends Canvas implements Runnable {// drawing area for the graph

final int MAXNODES = 20; final int MAX = MAXNODES+1; final int NODESIZE = 26; final int NODERADIX = 13; final int DIJKSTRA = 1; // basic graph information Point node[] = new Point[MAX]; // node

Page 20: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

int weight[][] = new int[MAX][MAX]; // weight of arrow Point arrow[][] = new Point[MAX][MAX]; // current position of arrowhead Point startp[][] = new Point[MAX][MAX]; // start and Point endp[][] = new Point[MAX][MAX]; // endpoint of arrow float dir_x[][] = new float[MAX][MAX]; // direction of arrow float dir_y[][] = new float[MAX][MAX]; // direction of arrow // graph information while running algorithm boolean algedge[][] = new boolean[MAX][MAX]; int dist[] = new int[MAX]; int finaldist[] = new int[MAX]; Color colornode[] = new Color[MAX]; boolean changed[] = new boolean[MAX]; // indicates distance change during algorithm int numchanged =0; int neighbours=0; int step=0; // information used by the algorithm to find the next // node with minimum distance int mindist, minnode, minstart, minend;

int numnodes=0; // number of nodes int emptyspots=0; // empty spots in array node[] (due to node deletion) int startgraph=0; // start of graph int hitnode; // mouse clicked on or close to this node int node1, node2; // numbers of nodes involved in current action

Point thispoint=new Point(0,0); // current mouseposition Point oldpoint=new Point(0, 0); // previous position of node being moved

// current action boolean newarrow = false; boolean movearrow = false; boolean movestart = false; boolean deletenode = false; boolean movenode = false; boolean performalg = false; boolean clicked = false;

// fonts Font roman= new Font("TimesRoman", Font.BOLD, 12); Font helvetica= new Font("Helvetica", Font.BOLD, 15); FontMetrics fmetrics = getFontMetrics(roman); int h = (int)fmetrics.getHeight()/3;

// for double buffering private Image offScreenImage; private Graphics offScreenGraphics; private Dimension offScreenSize;

// for run option Thread algrthm;

Page 21: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

// current algorithm, (in case more algorithms are added) int algorithm;

// algorithm information to be displayed in documetation panel String showstring = new String("");

boolean stepthrough=false;

// locking the screen while running the algorithm boolean Locked = false;

GraphAlgorithm parent;

GraphCanvas(GraphAlgorithm myparent) {parent = myparent;init();algorithm=DIJKSTRA;setBackground(Color.white);

}

public void lock() { // lock screen while running an algorithm

Locked=true; }

public void unlock() {Locked=false;

}

public void start() {if (algrthm != null) algrthm.resume () ;

}

public void init() {for (int i=0;i<MAXNODES;i++) { colornode[i]=Color.gray; for (int j=0; j<MAXNODES;j++) algedge[i][j]=false;}colornode[startgraph]=Color.blue;performalg = false;

}

public void clear() { // removes graph from screen

startgraph=0;numnodes=0;emptyspots=0;init();for(int i=0; i<MAXNODES; i++) { node[i]=new Point(0, 0); for (int j=0; j<MAXNODES;j++) weight[i][j]=0;}if (algrthm != null) algrthm.stop () ;parent.unlock();repaint();

}

Page 22: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

public void reset() { // resets a graph after running an algorithm

init();if (algrthm != null) algrthm.stop () ;parent.unlock();repaint();

}

public void runalg() { // gives an animation of the algorithm

parent.lock();initalg();performalg = true;algrthm = new Thread(this);algrthm.start();

}

public void stepalg() { // lets you step through the algorithm

parent.lock();initalg();performalg = true;nextstep();

}

public void initalg() {init();for(int i=0; i<MAXNODES; i++) { dist[i]=-1; finaldist[i]=-1; for (int j=0; j<MAXNODES;j++)

algedge[i][j]=false;}

dist[startgraph]=0;finaldist[startgraph]=0;step=0;

}

public void nextstep() { // calculates a step in the algorithm (finds a shortest // path to a next node). finaldist[minend]=mindist;

algedge[minstart][minend]=true;colornode[minend]=Color.green;

// build more information to display on documentation panelstep++;repaint();

}

public void stop() {if (algrthm != null) algrthm.suspend () ;

}

public void run() {for(int i=0; i<(numnodes-emptyspots); i++){ nextstep(); try { algrthm . sleep (1000) ; } catch (InterruptedException e) {}}

Page 23: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

algrthm = null; }

public void showexample() { // draws a default graph on the screen int w, h; clear(); init(); numnodes=6; emptyspots=0; for(int i=0; i<MAXNODES; i++) { node[i]=new Point(0, 0); for (int j=0; j<MAXNODES;j++) weight[i][j]=0; } w=this.size () .width/8; h=this.size () .height/8; node[0]=new Point(2*w, 4*h); node[1]=new Point(3*w, 2*h); node[2]=new Point(5*w, 2*h); node[3]=new Point(6*w, 4*h); node[4]=new Point(5*w, 6*h); node[5]=new Point(3*w, 6*h);

weight[0][1]=4; weight[1][0]=4; weight[0][5]=2; weight[5][0]=2; weight[1][2]=3; weight[2][1]=3; weight[1][4]=3; weight[4][1]=3; weight[2][3]=2; weight[3][2]=2; weight[3][4]=1; weight[4][3]=1; weight[4][5]=3; weight[5][4]=3;

for (int i=0;i<numnodes;i++) for (int j=0;j<numnodes;j++) if (weight[i][j]>0) arrowupdate(i, j, weight[i][j]);

repaint(); }

public boolean mouseDown(Event evt, int x, int y) {

if (Locked) parent.documentation.doctext.showline("locked");else { clicked = true; if (evt.shiftDown()) { // move a node if (nodehit(x, y, NODESIZE)) { oldpoint = node[hitnode]; node1 = hitnode; movenode=true; } } else if (evt.controlDown()) { // delete a node if (nodehit(x, y, NODESIZE)) { node1 = hitnode; if (startgraph==node1) {

Page 24: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

movestart=true; thispoint = new Point(x,y);

colornode[startgraph]=Color.gray; } else deletenode= true; } } else if (arrowhit(x, y, 5)) { // change weihgt of an edge movearrow = true; repaint(); } else if (nodehit(x, y, NODESIZE)) { // draw a new arrow if (!newarrow) { newarrow = true; thispoint = new Point(x, y); node1 = hitnode; } } else if ( !nodehit(x, y, 50) && !arrowhit(x, y, 50) ) { // draw new node if (emptyspots==0) { // take the next available spot in the array if (numnodes < MAXNODES) node[numnodes++]=new Point(x, y); else parent.documentation.doctext.showline("maxnodes"); } else { // take an empty spot in the array (from previously deleted

node) int i; for (i=0;i<numnodes;i++) if (node[i].x==-100) break; node[i]=new Point(x, y); emptyspots--; } } else // mouseclick to close to a point or arrowhead, so probably an

error parent.documentation.doctext.showline("toclose"); repaint();}return true;

}

public boolean mouseDrag(Event evt, int x, int y) {if ( (!Locked) && clicked ) { if (movenode) { // move node and adjust arrows coming into/outof the node node[node1]=new Point(x, y); for (int i=0;i<numnodes;i++) { if (weight[i][node1]>0) { arrowupdate(i, node1, weight[i][node1]); } if (weight[node1][i]>0) { arrowupdate(node1, i, weight[node1][i]);

Page 25: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

} } repaint(); } else if (movestart || newarrow) { thispoint = new Point(x, y); repaint(); } else if (movearrow) { changeweight(x, y); repaint(); }}return true;

}

public boolean mouseUp(Event evt, int x, int y) {if ( (!Locked) && clicked ) { if (movenode) { // move the node if the new position is not to close to // another node or outside of the panel node[node1]=new Point(0, 0); if ( nodehit(x, y, 50) || (x<0) || (x>this.size () .width) ||

(y<0) || (y>this.size () .height) ) { node[node1]=oldpoint; parent.documentation.doctext.showline("toclose"); } else node[node1]=new Point(x, y); for (int i=0;i<numnodes;i++) { if (weight[i][node1]>0) arrowupdate(i, node1, weight[i][node1]); if (weight[node1][i]>0) arrowupdate(node1, i, weight[node1][i]); } movenode=false; } else if (deletenode) { nodedelete(); deletenode=false; } else if (newarrow) { newarrow = false; if (nodehit(x, y, NODESIZE)) { node2=hitnode; if (node1!=node2) { arrowupdate(node1, node2, 50); if (weight[node2][node1]>0) { arrowupdate(node2, node1, weight[node2][node1]); } parent.documentation.doctext.showline("change weights"); } else System.out.println("zelfde"); } } else if (movearrow) { movearrow = false; if (weight[node1][node2]>0) changeweight(x, y);

Page 26: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

} else if (movestart) { // if new position is a node, this node becomes the startnode if (nodehit(x, y, NODESIZE)) startgraph=hitnode; colornode[startgraph]=Color.blue; movestart=false; } repaint();}return true;

}

public boolean nodehit(int x, int y, int dist) { // checks if you hit a node with your mouseclick

for (int i=0; i<numnodes; i++) if ( (x-node[i].x)*(x-node[i].x) +

(y-node[i].y)*(y-node[i].y) < dist*dist ) { hitnode = i; return true; }return false;

}

public boolean arrowhit(int x, int y, int dist) { // checks if you hit an arrow with your mouseclick

for (int i=0; i<numnodes; i++) for (int j=0; j<numnodes; j++) { if ( ( weight[i][j]>0 ) &&

(Math.pow(x-arrow[i][j].x, 2) + Math.pow(y-arrow[i][j].y, 2) < Math.pow(dist, 2) ) ) {

node1 = i; node2 = j; return true; } }return false;

}

public void nodedelete() { // delete a node and the arrows coming into/outof the node

node[node1]=new Point(-100, -100);for (int j=0;j<numnodes;j++) { weight[node1][j]=0; weight[j][node1]=0;}emptyspots++;

}

public void changeweight(int x, int y) { // changes the weight of an arrow (edge in the graph), when a user drags // the arrowhead over the edge connecting node node1 and node2.

// direction of the arrowint diff_x = (int)(20*dir_x[node1][node2]);int diff_y = (int)(20*dir_y[node1][node2]);

// depending on the arrow direction, follow the x, or the y

Page 27: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

// position of the mouse while the arrowhead is being draggedboolean follow_x=false; if (Math.abs(endp[node1][node2].x-startp[node1][node2].x) >

Math.abs(endp[node1][node2].y-startp[node1][node2].y) ) { follow_x = true;}

// find the new position of the arrowhead, and calculate // the corresponding weightif (follow_x) { int hbound = Math.max(startp[node1][node2].x,

endp[node1][node2].x)-Math.abs(diff_x); int lbound = Math.min(startp[node1][node2].x,

endp[node1][node2].x)+Math.abs(diff_x);

// arrow must stay between the nodes if (x<lbound) { arrow[node1][node2].x=lbound; } else if (x>hbound) { arrow[node1][node2].x=hbound; } else arrow[node1][node2].x=x;

arrow[node1][node2].y=(arrow[node1][node2].x-startp[node1][node2].x) * (endp[node1][node2].y-startp[node1][node2].y)/ (endp[node1][node2].x-startp[node1][node2].x) + startp[node1][node2].y;

// new weight weight[node1][node2]=

Math.abs(arrow[node1][node2].x-startp[node1][node2].x-diff_x)*100/(hbound-lbound);

}// do the same if you follow yelse { int hbound = Math.max(startp[node1][node2].y,

endp[node1][node2].y)-Math.abs(diff_y); int lbound = Math.min(startp[node1][node2].y,

endp[node1][node2].y)+Math.abs(diff_y);

if (y<lbound) { arrow[node1][node2].y=lbound; } else if (y>hbound) { arrow[node1][node2].y=hbound; } else arrow[node1][node2].y=y; arrow[node1][node2].x=

(arrow[node1][node2].y-startp[node1][node2].y) * (endp[node1][node2].x-startp[node1][node2].x)/

(endp[node1][node2].y-startp[node1][node2].y) + startp[node1][node2].x;

weight[node1][node2]=Math.abs(arrow[node1][node2].y-startp[node1][node2].y-diff_y)*

100/(hbound-lbound);}

}

public void arrowupdate(int p1, int p2, int w) { // make a new arrow from node p1 to p2 with weight w, or change // the weight of the existing arrow to w, calculate the resulting // position of the arrowhead

int dx, dy;float l;

Page 28: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

weight[p1][p2]=w;

// direction line between p1 and p2dx = node[p2].x-node[p1].x;dy = node[p2].y-node[p1].y;

// distance between p1 and p2l = (float)( Math.sqrt((float)(dx*dx + dy*dy)));dir_x[p1][p2]=dx/l;dir_y[p1][p2]=dy/l;

// calculate the start and endpoints of the arrow,// adjust startpoints if there also is an arrow from p2 to p1if (weight[p2][p1]>0) { startp[p1][p2] = new Point((int)(node[p1].x-5*dir_y[p1][p2]),

(int)(node[p1].y+5*dir_x[p1][p2])); endp[p1][p2] = new Point((int)(node[p2].x-5*dir_y[p1][p2]),

(int)(node[p2].y+5*dir_x[p1][p2]));}else { startp[p1][p2] = new Point(node[p1].x, node[p1].y); endp[p1][p2] = new Point(node[p2].x, node[p2].y);}

// range for arrowhead is not all the way to the start/endpointsint diff_x = (int)(Math.abs(20*dir_x[p1][p2]));int diff_y = (int)(Math.abs(20*dir_y[p1][p2]));

// calculate new x-position arrowheadif (startp[p1][p2].x>endp[p1][p2].x) { arrow[p1][p2] = new Point(endp[p1][p2].x + diff_x +

(Math.abs(endp[p1][p2].x-startp[p1][p2].x) - 2*diff_x )*(100-w)/100 , 0);

}else { arrow[p1][p2] = new Point(startp[p1][p2].x + diff_x +

(Math.abs(endp[p1][p2].x-startp[p1][p2].x) - 2*diff_x )*w/100, 0);

}

// calculate new y-position arrowheadif (startp[p1][p2].y>endp[p1][p2].y) { arrow[p1][p2].y=endp[p1][p2].y + diff_y +

(Math.abs(endp[p1][p2].y-startp[p1][p2].y) - 2*diff_y )*(100-w)/100;

}else { arrow[p1][p2].y=startp[p1][p2].y + diff_y +

(Math.abs(endp[p1][p2].y-startp[p1][p2].y) - 2*diff_y )*w/100;

} }

public String intToString(int i) {char c=(char)((int)'a'+i);return ""+c;

}

Page 29: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

public final synchronized void update(Graphics g) { // prepare new image offscreen

Dimension d=size () ;if ((offScreenImage == null) || (d.width != offScreenSize.width) ||

(d.height != offScreenSize.height)) { offScreenImage = createImage(d.width, d.height); offScreenSize = d; offScreenGraphics = offScreenImage.getGraphics();}offScreenGraphics.setColor(Color.white);offScreenGraphics.fillRect(0, 0, d.width, d.height);paint(offScreenGraphics);g.drawImage(offScreenImage, 0, 0, null);

}

public void drawarrow(Graphics g, int i, int j) { // draw arrow between node i and node j

int x1, x2, x3, y1, y2, y3;

// calculate arrowheadx1= (int)(arrow[i][j].x - 3*dir_x[i][j] + 6*dir_y[i][j]);x2= (int)(arrow[i][j].x - 3*dir_x[i][j] - 6*dir_y[i][j]);x3= (int)(arrow[i][j].x + 6*dir_x[i][j]);

y1= (int)(arrow[i][j].y - 3*dir_y[i][j] - 6*dir_x[i][j]);y2= (int)(arrow[i][j].y - 3*dir_y[i][j] + 6*dir_x[i][j]);y3= (int)(arrow[i][j].y + 6*dir_y[i][j]);

int arrowhead_x[] = { x1, x2, x3, x1 };int arrowhead_y[] = { y1, y2, y3, y1 };

// if edge already chosen by algorithm change colorif (algedge[i][j]) g.setColor(Color.green);// draw arrowg.drawLine(startp[i][j].x, startp[i][j].y, endp[i][j].x, endp[i]

[j].y);g.fillPolygon(arrowhead_x, arrowhead_y, 4);

// write weight of arrow at an appropriate positionint dx = (int)(Math.abs(7*dir_y[i][j]));int dy = (int)(Math.abs(7*dir_x[i][j]));String str = new String("" + weight[i][j]);g.setColor(Color.black);if ((startp[i][j].x>endp[i][j].x) && (startp[i][j].y>=endp[i][j].y)) g.drawString( str, arrow[i][j].x + dx, arrow[i][j].y - dy);if ((startp[i][j].x>=endp[i][j].x) && (startp[i][j].y<endp[i][j].y)) g.drawString( str, arrow[i][j].x - fmetrics.stringWidth(str) -

dx , arrow[i][j].y - dy);

if ((startp[i][j].x<endp[i][j].x) && (startp[i][j].y<=endp[i][j].y)) g.drawString( str, arrow[i][j].x - fmetrics.stringWidth(str) ,

arrow[i][j].y + fmetrics.getHeight());if ((startp[i][j].x<=endp[i][j].x) && (startp[i][j].y>endp[i][j].y)) g.drawString( str, arrow[i][j].x + dx,

arrow[i][j].y + fmetrics.getHeight() );

}

Page 30: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

public void detailsDijkstra(Graphics g, int i, int j) { // check arrow between node i and node j is amongst the arrows to // choose from during this step of the algorithm // check if node j has the next minimal distance to the startnode

if ( (finaldist[i]!=-1) && (finaldist[j]==-1) ) { g.setColor(Color.red); if ( (dist[j]==-1) || (dist[j]>=(dist[i]+weight[i][j])) ) {

if ( (dist[i]+weight[i][j])<dist[j] ) { changed[j]=true; numchanged++; }

dist[j] = dist[i]+weight[i][j]; colornode[j]=Color.red; if ( (mindist==0) || (dist[j]<mindist) ) { mindist=dist[j]; minstart=i; minend=j; } }}else g.setColor(Color.lightGray);

}

public void endstepDijkstra(Graphics g) { // displays current and final distances of nodes, sets the final distance // for the node that had minimal distance in this step // explains algorithm on documentation panel for (int i=0; i<numnodes; i++)

if ( (node[i].x>0) && (dist[i]!=-1) ) { String str = new String(""+dist[i]); g.drawString(str, node[i].x - (int)fmetrics.stringWidth(str)/2

-1, node[i].y + h);

// string to distance to nodes on the documentation panel if (finaldist[i]==-1) { neighbours++; if (neighbours!=1) showstring = showstring + ", "; showstring = showstring + intToString(i) +"=" + dist[i]; } }

showstring = showstring + ". "; if ( (step>1) && (numchanged>0) ) { if (numchanged>1) showstring = showstring + "Notice that the distances to "; else showstring = showstring + "Notice that the distance to "; for (int i=0; i<numnodes; i++) if ( changed[i] ) showstring = showstring + intToString(i) +", "; if (numchanged>1) showstring = showstring + "have changed!\n"; else showstring = showstring + "has changed!\n"; } else showstring = showstring + " ";

if (neighbours>1) { // if there where more canditates explain why this node is taken

showstring = showstring + "Node " + intToString(minend) +

Page 31: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

" has the minimum distance.\n"; //check if there are other paths to minend. int newpaths=0; for (int i=0; i<numnodes; i++) if ( (node[i].x>0) && (weight[i][minend]>0) && ( finaldist[i]

== -1 ) ) newpaths++; if (newpaths>0) showstring = showstring + "Any other path to " +

intToString(minend) + " visits another red node, and will be longer than " + mindist + ".\n"; else showstring = showstring +

"There are no other arrows coming in to "+ intToString(minend) + ".\n";

}else {

boolean morenodes=false; for (int i=0; i<numnodes; i++)

if ( ( node[i].x>0 ) && ( finaldist[i] == -1 ) && ( weight[i][minend]>0 ) )

morenodes=true; boolean bridge=false; for (int i=0; i<numnodes; i++)

if ( ( node[i].x>0 ) && ( finaldist[i] == -1 ) && ( weight[minend][i]>0 ) )

bridge=true; if ( morenodes && bridge ) showstring = showstring + "Since this node forms a 'bridge' to "+ "the remaining nodes,\nall other paths to this node will be longer.\n"; else if ( morenodes && (!bridge) ) showstring = showstring + "Remaining gray nodes are not reachable.\n"; else showstring = showstring + "There are no other arrows coming in to "+

intToString(minend) + ".\n"; }

showstring = showstring + "Node " + intToString(minend) + " will be colored green to indicate " + mindist + " is the length of the shortest path to " + intToString(minend)

+"."; parent.documentation.doctext.showline(showstring);

}

public void detailsalg(Graphics g, int i, int j) { // more algorithms can be added later

if (algorithm==DIJKSTRA) detailsDijkstra(g, i, j);

}

public void endstepalg(Graphics g) { // more algorithms can be added later

if (algorithm==DIJKSTRA) endstepDijkstra(g);if ( ( performalg ) && (mindist==0) ) { if (algrthm != null) algrthm.stop () ;

Page 32: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

int nreachable = 0; for (int i=0; i<numnodes; i++) if (finaldist[i] > 0)

nreachable++; if (nreachable == 0) parent.documentation.doctext.showline("none");

else if (nreachable< (numnodes-emptyspots-1)) parent.documentation.doctext.showline("some"); else parent.documentation.doctext.showline("done");}

}

public void paint(Graphics g) { mindist=0;

minnode=MAXNODES;minstart=MAXNODES;minend=MAXNODES;

for(int i=0; i<MAXNODES; i++) changed[i]=false; numchanged=0; neighbours=0;

g.setFont(roman);g.setColor(Color.black);

if (step==1) showstring="Algorithm running: red arrows point to nodes reachable from " + " the startnode.\nThe distance to: "; else showstring="Step " + step + ": Red arrows point to nodes reachable from " + "nodes that already have a final distance." + "\nThe distance to: ";

// draw a new arrow upto current mouse positionif (newarrow) g.drawLine(node[node1].x, node[node1].y, thispoint.x,

thispoint.y);

// draw all arrowsfor (int i=0; i<numnodes; i++) for (int j=0; j<numnodes; j++) if (weight [i][j]>0) { // if algorithm is running then perform next step for this

arrow if (performalg) detailsalg(g, i, j); drawarrow(g, i, j); }

// if arrowhead has been dragged to 0, draw it anyway, so the user// will have the option to make it positive againif (movearrow && weight[node1][node2]==0) { drawarrow(g, node1, node2); g.drawLine(startp[node1][node2].x, startp[node1][node2].y,

endp[node1][node2].x, endp[node1][node2].y);}

// draw the nodes

Page 33: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

for (int i=0; i<numnodes; i++) if (node[i].x>0) { g.setColor(colornode[i]); g.fillOval(node[i].x-NODERADIX, node[i].y-NODERADIX,

NODESIZE, NODESIZE); }

// reflect the startnode being movedg.setColor(Color.blue);if (movestart) g.fillOval(thispoint.x-NODERADIX, thispoint.y-NODERADIX,

NODESIZE, NODESIZE);

g.setColor(Color.black);// finish this step of the algorithmif (performalg) endstepalg(g);

// draw black circles around nodes, write their names to the screeng.setFont(helvetica);for (int i=0; i<numnodes; i++) if (node[i].x>0) { g.setColor(Color.black); g.drawOval(node[i].x-NODERADIX, node[i].y-NODERADIX,

NODESIZE, NODESIZE); g.setColor(Color.blue); g.drawString(intToString(i), node[i].x-14, node[i].y-14); }

}}

Class GraphAlgorithm:

Class GraphAlgorithm là Class main của chương trình, chứa các Class còn lại

và là Class chạy thực thi chương trình.

package Dijkstra3;

import java.awt.*;import javax.swing.*;

/** * GraphAlgorithm.java * * @author: Nhanntv * @date: November, 2011 * * Applet for explaining graph algorithms. * It currently only explains Dijkstra's shortest path algorithm, * but it can easily be extended to handle more algorithms. * * Copyright 2011, Nhanntv, all rights reserved */

Page 34: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

public class GraphAlgorithm extends java.applet.Applet {

GraphCanvas graphcanvas = new GraphCanvas(this); //Graphics Dijkstra Options options = new Options(this); //Option Documentation documentation = new Documentation(); //document instruction //Ham khoi tao public void init() { setSize(700,500);

setLayout(new BorderLayout(10, 10));add("Center", graphcanvas);add("North", documentation);add("East", options);

} public void start(){ super.start(); }

public Insets insets() {return new Insets(10, 10, 10, 10);

} //Ham Lock public void lock() {

graphcanvas.lock();options.lock();

}

//Ham Unlock public void unlock() {

graphcanvas.unlock();options.unlock();

} }

Đầu vào:

Ta có thể vẽ mạng ngay trong phần mềm và sau đó chạy thực thi chương trình

để tìm đường đi ngắn nhất trong mạng. Trong chương trình còn có ví dụ minh họa cho

sẵn để giúp người sử dụng dễ hình dung được về chương trình.

Các bước để vẽ một mạng được hướng dẫn cụ thể trong Documentation. Ta có

thể vẽ một mạng như ví dụ đã cho ban đầu như sau. Sử dụng chuột click lên screen của

ứng dụng để vẽ các đỉnh (đỉnh màu xanh là đỉnh xuất phát). Click vào một đỉnh và rê

chuột đến đỉnh khác để thiết lập chi phí (khoảng cách) giữa 2 đỉnh. Click vào các mũi

tên màu đen và kéo rê chuột đểt thay đổi chi phí (khoảng cách) giữa 2 đỉnh.

Page 35: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Hoặc ta có thể chọn ví dụ cho sẵn bằng cách nhấn Button Example.

Page 36: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Đầu ra (output):

Ta có thể xem từng bước thực hiện chương trình bằng cách nhấn Button Step

hoặc cho chương trình tự chạy đến khi kết thúc bằng cách nhấn Button Run.

Kết quả hiển thị lên màn hình là đồ thị đường đi ngắn nhất trong mạng với đỉnh

xuất phát (màu xanh dương) và các đỉnh còn lại màu xanh lá cây. Đường đi ngắn nhất

qua các đỉnh sẽ được hiển thị màu xanh lá cây và trọng số từ đỉnh xuất phát đến các

đỉnh kia sẽ được hiện thị ở bên trong hình trong mô tả đỉnh.

Kết quả của ví dụ đã cho sẽ được minh họa như sau:

Page 37: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Kết quả của Example được minh họa như sau:

Page 38: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Ưng dung đôi vơi Open Shortest Path First (OSPF):Khai quat vê Open Shortest Path First:

Open Shortest Path Fisrt (OSPF) đươc phat triên bơi Internet Engineering Task

Force (IETF) như môt sư thay thê nhưng han chê cung như nhươc điêm cua RIP.

OSPF la môt link state protocol-như tên goi cua minh no sư dung thuât toan

Dijkstra Shortest Path First (SPF) đê xây dưng routing table va open noi lên tinh phô

biên cua no. OSPF đa đươc John Moy đưa ra thông qua môt sô RFC, gân đây nhât la

RFC 2328.

Giông như cac link state protocol, OSPF co ưu điêm la hôi tu nhanh, hô trơ

đươc mang co kich thươc lơn va không xay ra routing loop. Bên canh đo OSPF con co

nhưng đăc trưng:

+Sư dung area đê giam yêu câu vê CPU, memory cua OSPF router cung như

lưu lương đinh tuyên co thê xây dưng hierarchical internetwork topologies.

+La giao thưc đinh tuyên dang classless nên hô trơ đươc VLSM va discontigous

network.

+OSPF sư dung đia chi multicast 224.0.0.5 (all SPF router) 224.0.0.6 (DR va

BDR router) đê gưi cac thông điêp Hello va Update.

+OSPF con co kha năng hô trơ chưng thưc dang plain text va dang MD5.

Hoat đông cua OSPF (Operation of OSPF): Cac OSPF-speaking router gưi cac Hello packet ra tât ca cac OSPF-enable

interface. Nêu hai router sau khi trao đôi Hello packet va thoa thuân môt sô thông sô thi

chung se trơ thanh “hang xom” (neightbor).

Adjacency co thê đươc tao qua virtual point-to-point link hay đươc tao qua môt

vai neighbor. OSPF đinh nghia ra môt sô loai network va môt sô loai router. Sư thiêt

lâp môt adjacency đươc xac đinh bơi loai router trao đôi Hello va loai network ma

Hello trao đôi qua.

Môi router gưi cac link state advertisement (LSA) qua tât ca adjacency. LSA

mô ta tât ca cac interface cua router (link) va trang thai cua link. Cac link nay co thê la

stub network, tơi OSPF router khac, tơi network trong cung môt area, tơi external

Page 39: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

network. Do co rât nhiêu loai link state information cho nên OSPF đinh nghia đên 11

loai LSA.

Môi router nhân môt LSA tư neighbor vơi link state database cua neighbor đo

va gưi môt ban copy cua LSA đên tât ca neighbor khac cua no.

Băng cach flooding cac LSA toan bô môt area, tât ca router se xây dưng chinh

xac link state database.

Khi database đươc hoan tât, môi router sư dung thuât toan SPF đê xây dưng nên

SPF tree.

Môi router se xây dưng nên routing table tư SPF tree.

Tinh toan SPF tree: Shortest Path First (SPF) la nhưng tuyên đương qua mang tơi bât ki đich nao.

Co hai loai đich đươc thưa nhân trong OSPF.

Network router:

La cac area border router (ABR) va autonomous system boundary router

(ASBR).

Chi môt lân sau khi tât ca cac OSPF router đông bô đươc link state database,

môi router se tinh toan SPF tree cho môi đich ma no biêt. Sư tinh toan nay đươc thưc

hiên bơi thuât toan Dijkstra.

Page 40: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing

Hinh 6. Thuât toan Dijkstra biêu diên SPF tree.

Metric cua OSPF :

OSPF đê câp đên metric la cost. Cost cua toan tuyên la tông cua cost cua cac

outgoing interface doc theo tuyên đương đo. Cach tinh cost đươc IETF đưa ra trong

RFC 2328. Cisco đa thưc thi cach tinh cost cua riêng minh như sau:

108/bandwidth vơi gia tri bandwidth đươc câu hinh cho môi interface.

Page 41: Giai Thuat Dijkstra Cho Sortest Path Routing

Ứng dụng thuật toán Dijkstratrong Shortest Path Routing