Showing posts with label Góc học tập. Show all posts
Showing posts with label Góc học tập. Show all posts

[C\C++] Cài đặt thuật toán duyệt Đồ thị (DFS, BFS) [Lý thuyết đồ thị]

Cài đặt thuật toán: Duyệt đồ thị theo chiều rộng (BFS) và chiều sâu (DFS)



[C\C++] Cài đặt thuật toán duyệt Đồ thị (DFS, BFS) [Lý thuyết đồ thị]
[C\C++] Cài đặt thuật toán duyệt Đồ thị (DFS, BFS) [Lý thuyết đồ thị]

/* Duyệt đồ thị theo chiều rộng (BFS) và chiều sâu (DFS) */
// Code Turbo C++ #include<conio.h>
#include<iostream.h>
#include<stdlib.h>

void create();  // For creating a graph
void dfs();  // For Deapth First Search(DFS) Traversal.
void bfs();  // For Breadth First Search(BFS) Traversal.

struct node  // Structure for elements in the graph
{
   int data,status;
   struct node *next;
   struct link *adj;
};

struct link  // Structure for adjacency list
{
   struct node *next;
   struct link *adj;
};

struct node *start,*p,*q;
struct link *l,*k;
int main()
{
   int chon;
   create();
   
   while(1)
   
   { 
 cout<<"\nMENU:\n";
      cout<<"1: DFS\n";
 cout<<"2: BSF\n";
      cout<<"3: Exit\n";
      cout<<" Nhap vao su lua chon cua ban : \n";
      cin>>chon;
      switch(chon)
      {
case 1:
   dfs();
   break;
case 2:
        bfs();
   break;
case 3:
   exit(0);
   break;
default:
   cout<<"Chon khong dung!\n";
cout<<"Nhap lai luc chon.\n";
   getch();
      }
   }
   return 0;
}

void create()    // Creating a graph
{
   int dat,flag=0;
   start=NULL;
   cout<<"Nhap cac nut trong do thi (nhap 0 de ket thuc): \n";
   while(1)
   {
      cin>>dat;
      if(dat==0)
break;
      p=new node;
      p->data=dat;
      p->status=0;
      p->next=NULL;
      p->adj=NULL;
      if(flag==0)
      {
start=p;
q=p;
flag++;
      }
      else
      {
q->next=p;
q=p;
      }
   }
   p=start;
   while(p!=NULL)
   {
      cout<<"Cac nut noi ke voi "<<p->data<<" (nhap 0 de ket thuc) : \n";
      flag=0;
      while(1)
      {
cin>>dat;
if(dat==0)
   break;
k=new link;
k->adj=NULL;
if(flag==0)
{
   p->adj=k;
   l=k;
   flag++;
}
else
{
   l->adj=k;
   l=k;
}
q=start;
while(q!=NULL)
{
   if(q->data==dat)
      k->next=q;
   q=q->next;
}
      }
      p=p->next;
   }
   cout<<"\n-------------------------\n";
   return;
}
//Deapth First Search(DFS) Traversal.

void bfs()
{
   int qu[20],i=1,j=0;
   p=start;
   while(p!=NULL)
   {
      p->status=0;
      p=p->next;
   }
   p=start;
   qu[0]=p->data;
   p->status=1;
   while(1)
   {
      if(qu[j]==0)
break;
      p=start;
      while(p!=NULL)
      {
if(p->data==qu[j])
    break;
p=p->next;
      }
      k=p->adj;
      while(k!=NULL)
      {
q=k->next;
if(q->status==0)
{
   qu[i]=q->data;
   q->status=1;
   qu[i+1]=0;
   i++;
}
k=k->adj;
      }
      j++;
   }
   j=0;
   cout<<"Ket qua theo BFS:  ";
   while(qu[j]!=0)
   {
      cout<<qu[j]<<"  ";
      j++;
   }
   getch();
   return;
}


// Breadth First Search(BFS) Traversal.
void dfs()
{
   int stack[25],top=1;
   cout<<"Ket qua theo DFS:  ";
   p=start;
   while(p!=NULL)
   {
      p->status=0;
      p=p->next;
   }
   p=start;
   stack[0]=0;
   stack[top]=p->data;
   p->status=1;
   while(1)
   {
      if(stack[top]==0)
break;
      p=start;
      while(p!=NULL)
      {
if(p->data==stack[top])
   break;
p=p->next;
      }
      cout<<stack[top]<<"  ";
      top--;
      k=p->adj;
      while(k!=NULL)
      {
q=k->next;
if(q->status==0)
{
   top++;
   stack[top]=q->data;
   q->status=1;
}
k=k->adj;
      }
   }
   getch();
   return;
}

//---------------------------



Chúc các bạn thành công!

 

* Có thể bản quan tâm: [MMO] Hướng Dẫn *Kiếm Tiền Tự Động* Với Các Ứng Dụng Treo Máy *CỰC KỲ ĐƠN GIẢN VÀ HIỆU QUẢ*




[ C\C++ ] Ví dụ mảng 2 chiều trong C\C++


/*
Vi du 1 [ mang 2 chieu ]
 - Nhap vao tu ban phim ma tran vuong chua cac so nguyen co kich thuoc n (3<=n<=8)
 - In ma tran vua nhap
 - Dem so chan trong ma tran
 - Tinh tong theo dong cua ma tran
 - Tim so lon nhat, nho nhat tron ma tran
 - In ra vi tri xuat hien cac so nguyen to trong ma tran

*/
#include<iostream.h>
#include<conio.h>
// khai bao ma tran
int a[8][8],n;
// nhap ma tran
 void Nhap(){ 
 // nhap n 
  do{  
   cout<<"\n n= "; 
   cin>>n;  
   if(n<3||n>8) 
      cout<<"\n Nhap lai n!"; 
 }while(n<3||n>8); 

// Nhap ma tran 

cout<<"\n Nhap ma tran: "; 

for(int i=0;i<n;i++)  
   for(int j=0;j<n;j++) 
    {  
      cout<<"\n a["<<i<<"]["<<j<<"]= ";  
      cin>>a[i][j]; 
    }
   }

// In ma tran
void InMaTran(){ 
  cout<<"\n IN MA TRAN VUA NHAP: \n"; 
  for(int i=0;i<n;i++) {  
    for(int j=0;j<n;j++) 
      cout<<a[i][j]<<"\t";  cout<<"\n"; 
    }
   }

// Dem so phan tu chan trong ma tran
int DemSoChan(){ 
  int d=0; for(int i=0;i<n;i++)  
     for(int j=0;j<n;j++) 
       if(a[i][j]%2==0) 
         d++;  
    return d;
 }

// Tinh tong dong
void TongDong(){ 
 cout<<"\n Tong theo dong cua ma tran: \n"; 
  int s; 
  for(int i=0;i<n;i++) {  
   s=0;  
   for(int j=0;j<n;j++)  
      s=s+a[i][j];  
      cout<<"\n Tong dong "<<i<<" : "<<s;  
  }
 }

// Ham kiem tra so nguyen to
int TestSoNT(int a){ 
  for(int i=2;i<a;i++)  
     if(a%i==0) return 0;
 return 1; 
} 

// In ra vi tri so nguyen to
void ViTriSoNT(){  
 cout<<"\n VI TRI CAC SO NGUYEN TO TRONG MA TRAN: \n";  
 for (int i=0;i<n;i++)  
   for(int j=0;j<n;j++)
     if(TestSoNT(a[i][j])==1)
       cout<<"["<<i<<"]["<<j<<"] ;";
}

// ham chinh

void main(){  
clrscr();  
Nhap(); 
InMaTran();  
cout<<"\n So so chan trong ma tran: "<<DemSoChan();  
TongDong();  
ViTriSoNT();  
getch();

}

[ C\C++ ] Ví dụ: nhúng Assembly trong C\C++ [ Assembly ]

Nhúng Assembly trong C\C++:

* Ví dụ 1:
  - Nhập vào số nguyên n (1<=n<=10, n chẵn)
  - Tính S=2!+4!+6!+...+n!

[Code Turbo C++]
/* Nhúng mã Assembly trong C++ */

#include<iostream.h>
#include<conio.h>

// khai bao
int n;

// Nhap n (thoa man 1 <= n <= 10, n la so chan)
void Nhap(){
  cout<<"\n - Nhap n: ";
  do{
     cout<<"\n n= "; cin>>n;
     if(n<1||n>10||n%2!=0)
         cout<<"\n Nhap lai n!";
   } while(n<1||n>10||n%2!=0);
}

// Tinh giai thua
int GiaiThua(int a){
   int gt=1;
                // for(int i=1;i<=a;i++)
                //     gt*=i;
// nhung assembly
    char a1 =(char)a;
    asm xor ax,ax    // xoa thanh ghi ax
    asm mov bl,1    // bien chi so
    Tinh:
           asm mov ax,gt     // ax=gt
           asm mul bl          // ax=ax*bl
           asm mov gt,ax     // gt=ax
           asm inc bl           // bl=bl+1
           asm cmp bl,a1     // so sanh bl voi a1
           asm jg Thoat1     // nhay neu bl > a1
           asm jmp Tinh
     
     Thoat1:
      return gt;
}


// Tinh tong s=2!+4!+6!+...+n!
int TongGT(int n){
    int tong=0;
                   // for(int i=2;i<=n;i=i+2)
                   //       tong=tong+GiaiThua(i);
     int gt;
     char j, t=(char)n;
// Nhung Assembly
     asm xor dx,dx   // xoa dx
     asm mov bh,2   // i=2
     Tinh1:
              asm mov j,bh       // j=bh
              asm mov dx,tong  // dx=tong
              gt=GiaiThua(j);
              asm add dx,gt       // dx=dx+gt
              asm mov tong,dx  // tong=dx
              asm add bh,2        // bh=bh+2
              asm cmp bh,t        // so sanh bh voi t
              asm jg Thoat2       // nhay neu bh > t
              asm jmp Tinh1

      Thoat2:
       return tong;
}

// ham chinh-----------------
void main(){
   Nhap();
   // in ket qua
   cout<<"\n - Tong S= "<<TongGT(n);
   getch();

}

[Tải chương trình về máy tại đây]
--------------------------------------------------------
* Ví dụ 2: 
 - Nhập vào ma trận vuông chứa 0/1, kích thước n (1 < n < 6)
 - In ma trận vừa nhập
 - Số lần xuất hiện của số 1
 - Kiểm tra tính đối xứng của ma trận

[Code Turbo C++]
#include<iostream.h>
#include<conio.h>

void main(){
 // khai bao
 int a[5][5],n;
 int i,j;
 // nhap n
 do{
  cout<<"\n n= "; cin>>n;
  if(n<2||n>5)
cout<<"\n Nhap lai n!";
 }while(n<2||n>5);

 // nhap ma tran
 for(i=0;i<n;i++)
  for(j=0;j<n;j++)
do{
cout<<"\n a["<<i<<"]["<<j<<"]= "; cin>>a[i][j];
if(a[i][j]!=1&&a[i][j]!=0)
cout<<"\n Nhap lai a["<<i<<"]["<<j<<"] !";
}while(a[i][j]!=1&&a[i][j]!=0);

  // in ma tran

 for(i=0;i<n;i++)
 {
for(j=0;j<n;j++)
cout<<a[i][j]<<"\t";
  cout<<"\n";
  }

/* dem so lan xuat hien cua 1 (nhung assembly) */
  // chuyen doi mang a thanh mang 1 chieu
  int a1[25];
  int k=0;
  for(i=0;i<n;i++)
for(j=0;j<n;j++)
 a1[k++]=a[i][j];
// thuc hien dem
  int size=n*n, dem=0;
  asm mov ax,0 // chua bien dem
  asm lea dx,a1
  asm mov di,dx
  asm mov bx,0
  Dem1:
 asm cmp bx,size
 asm je Thoat
 asm mov dx,[di]
 asm cmp dx, 1
 asm je bang
 asm jmp khongbang
 bang:
asm inc ax
 khongbang:
asm inc di
asm inc di
asm inc bx
asm jmp Dem1
Thoat:
 asm mov dem,ax
cout<<"\n - So lan xuat hien cua 1 :"<<dem;

/* kiem tra tinh doi xung */
  char n1=(char)n,j1;
  int t,t1,t2;
  asm mov cx,0
  for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
t=a[i][j1];
t1=a[j1][i];
asm mov ax,t1
asm mov dx,t
asm cmp ax,dx
asm jne KhacNhau
asm jmp Lap1
KhacNhau:
 asm mov cx,1
 break;
Lap1:
}

asm mov t2,cx
if (t2==0)
cout<<"\n - Ma tran doi xung !";
else
 cout<<"\n - Ma tran khong doi xung !";


 getch();
}

[C\C++] Bài tập: Cấu trúc if [160915]

[C\C++] Bài tập: Cấu trúc if [160915] (Chưa bài tập về nhà, lớp ĐH Tin K6 - TDU)

// --------------------
Bài 1. Giải và biện luận ax^2 + bx + c=0
//---------------------
/* Viết trên DEV C++*/

/* Cách 1: (không sử dụng chương trình con- hàm) */

#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
// hàm chính
int main(){
// khai bao bien
float a,b,c;
// Nhap
cout<<"\n Nhap he so:";
cout<<"\n a: "; cin>>a;
cout<<"\n b: "; cin>>b;
cout<<"\n c: "; cin>>c;
// Bien luan
if(a==0)
if(b==0)
if(c==0)
cout<<"\n Phuong trinh vo so nghiem";
else
cout<<"\n Phuong trinh vo nghiem";
else
cout<<"\n Phuong trinh co 1 nghiem x="<<-c/b;
else
{
// tinh delta
float d=b*b-4*a*c;
if(d<0)
cout<<"\n Phuong trinh vo nghiem";
if(d==0)
cout<<"\n Phuong trinh co nghiem kep x1=x2="<<-b/(2*a);
if(d>0)
{
float x1= (-b-sqrt(d))/(2*a), x2=(-b+sqrt(d))/(2*a);
cout<<"\n Phuong trinh co 2 nghiem x1="<<x1<<"; x2="<<x2;
}
}
getch();
return 0;
}


//-------------------------------------------------
/* Cách 2: (sử dụng chương trình con- hàm) */

#include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
float a,b,c;
// Ham hap he so
void NhapHS(){
cout<<"\n Nhap he so:";
cout<<"\n a: "; cin>>a;
cout<<"\n b: "; cin>>b;
cout<<"\n c: "; cin>>c;
}
// Ham giai va bien luan
void GiaiPT(float a, float b, float c){
if(a==0)
if(b==0)
if(c==0)
cout<<"\n Phuong trinh vo so nghiem";
else
cout<<"\n Phuong trinh vo nghiem";
else
cout<<"\n Phuong trinh co 1 nghiem x="<<-c/b;
else
{
// tinh delta
float d=b*b-4*a*c;
if(d<0)
cout<<"\n Phuong trinh vo nghiem";
if(d==0)
cout<<"\n Phuong trinh co nghiem kep x1=x2="<<-b/(2*a);
if(d>0)
{
float x1= (-b-sqrt(d))/(2*a), x2=(-b+sqrt(d))/(2*a);
cout<<"\n Phuong trinh co 2 nghiem x1="<<x1<<"; x2="<<x2;
}
}
}
// hàm chính
int main(){
// goi ham
NhapHS();
GiaiPT(a,b,c);
getch();
return 0;
}

//---------------------------------------------------
Bài 2:
- Nhập vào điểm Toán rời rạc
- In ra điểm chữ
- Tính điểm tích lũy
(0<= điểm <=10)
//----------------------------------------------------

/* Viết trên DEV C++*/

#include<iostream>
#include<conio.h>
using namespace std;
int main(){
// Khai bao bien
float diemTRR;
// Nhap diem
cout<<"\n Nhap diem TRR: ";
cin>>diemTRR;
if(diemTRR<0 || diemTRR>10)
cout<<"\n Gia tri nhap vao khong phu hop!";
else
{
// diem chu
char diemChu; if(diemTRR<4)
diemChu='F';
  else if(diemTRR<5.5)
diemChu='D';
else if(diemTRR<7)
diemChu='C';
else if(diemTRR<7)
diemChu='B';
else if(diemTRR<8.5)
diemChu='B';
else diemChu='A'; // Diem tich luy
float diemTL;
if(diemChu=='F')
diemTL=0;
  else if(diemChu=='D')
diemTL=1;
else if(diemChu=='C')
diemTL=2;
else if(diemChu=='B')
diemTL=3;
else
diemTL=4;
// in ket qua
cout<<"\n * Diem so: "<<diemTRR;
cout<<"\n * Diem chu: "<<diemChu;
cout<<"\n * Diem tich luy: "<<diemTL; }
getch();
return 0;
}
// Các bạn có thể triển khai code theo cách khác.

>> TẢI VỀ TẠI ĐÂY

[Java] Ví dụ Giải phương trình bậc 2 sử dụng Java G.U.I [Java GUI - Giao diện đồ họa trong Java]

Xây dựng Project Giải phương trình bậc 2 (ax^2 + bx +c =0) sử dụng GUI.

Thực hiện:
1. Xây dựng Project như hình vẽ

Trong đó:
 + class GPTB2_GUI: Chứa thiết kế giao diện và phương thức chính
 + class GPTB2: Giải và biện luận phương trình bậc 2

2. Thiết kế giao diện (code thiết kế trong class GPTB2_GUI)



3. Java Code
+ class GPTB2_GUI -----------------------------------------------------

package gptb2_gui;

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

public class GPTB2_GUI  extends JFrame {
private static final long serialVersionUID = 1L;

public GPTB2_GUI(String title)
{
    setTitle(title);
}
// Hiển thị
public void doShow()
{
    setSize(400, 300);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    addControl();
    setResizable(false);
    setVisible(true);
}

// Thiết kế giao diện
public void addControl()
{
    JPanel pnBorder=new JPanel();
    pnBorder.setLayout(new BorderLayout());
    // tiêu đề
    JPanel pnNorth=new JPanel();
    JLabel lblTitle=new JLabel("Giải phương trình bậc 2");
    pnNorth.add(lblTitle);
    pnBorder.add(pnNorth,BorderLayout.NORTH);
    lblTitle.setForeground(Color.BLUE);
    Font ft=new Font("arial", Font.BOLD, 25);
    lblTitle.setFont(ft);
    // button
    JPanel pnSouth=new JPanel();
    JButton btnGiai=new JButton("Giải");
    JButton btnXoa=new JButton("Xóa");
    JButton btnThoat=new JButton("Thoát");
    pnSouth.add(btnGiai);
    pnSouth.add(btnXoa);
    pnSouth.add(btnThoat);
    pnBorder.add(pnSouth,BorderLayout.SOUTH);
    pnSouth.setBackground(Color.LIGHT_GRAY);
    Border  southborder=BorderFactory.createLineBorder(Color.RED);
    TitledBorder southTitleBorder=new TitledBorder(southborder, "Chọn tác vụ");
    pnSouth.setBorder(southTitleBorder);
    // panel nhap
    JPanel pnCenter=new JPanel();
    pnCenter.setLayout(new BoxLayout(pnCenter, BoxLayout.Y_AXIS));
    pnBorder.add(pnCenter,BorderLayout.CENTER);
    Border  centerborder=BorderFactory.createLineBorder(Color.RED);
    TitledBorder centerTitleBorder=new TitledBorder(centerborder, "Nhập hệ số a, b, c:");
    pnCenter.setBorder(centerTitleBorder);
    // hệ số a
    JPanel pna=new JPanel();
    JLabel lbla=new JLabel("Nhập a:");
    final JTextField txta=new  JTextField(15);
    pna.add(lbla);
    pna.add(txta);
    pnCenter.add(pna);
    // hệ số b
    JPanel pnb=new JPanel();
    JLabel lblb=new JLabel("Nhập b:");
    final JTextField txtb=new  JTextField(15);
    pnb.add(lblb);
    pnb.add(txtb);
    pnCenter.add(pnb);
    // hệ số c
    JPanel pnc=new JPanel();
    JLabel lblc=new JLabel("Nhập c:");
    final JTextField txtc=new  JTextField(15);
    pnc.add(lblc);
    pnc.add(txtc);
    pnCenter.add(pnc);
    // hệ số kq
    JPanel pnkq=new JPanel();
    JLabel lblkq=new JLabel("kết quả:");
    final JTextField txtkq=new  JTextField(15);
    pnkq.add(lblkq);
    pnkq.add(txtkq);
    pnCenter.add(pnkq);
    
    lbla.setPreferredSize(lblkq.getPreferredSize());
    lblb.setPreferredSize(lblkq.getPreferredSize());
    lblc.setPreferredSize(lblkq.getPreferredSize());
    
    // sự kiện thoát
    btnThoat.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            int ret=JOptionPane.showConfirmDialog(null, "Thoát khỏi chương trình ?", "Thoát", JOptionPane.YES_NO_OPTION);
            if(ret==JOptionPane.YES_OPTION)
                System.exit(0);
        }
    });
    // sự kiện xóa
    btnXoa.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            txta.setText("");
            txtb.setText("");
            txtc.setText("");
            txtkq.setText("");
            txta.requestFocus();
        }
    });
    // sự kiện giải
    btnGiai.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            String sa=txta.getText();
            float a=0,b=0,c=0;
            try
                {
                    a=Float.parseFloat(sa);;
                }
            catch(Exception ex)
                {
                    JOptionPane.showMessageDialog(null, "Nhập sai định dạng!");
                    txta.selectAll();
                    txta.requestFocus();
                    return;
                }
            String sb=txtb.getText();
            try
            {
                b=Float.parseFloat(sb);
            }
            catch(Exception ex)
            {
                JOptionPane.showMessageDialog(null, "Nhập sai định dạng!");
                txtb.selectAll();
                txtb.requestFocus();
                return;
             }
            String sc=txtc.getText();
            try
            {
                c=Float.parseFloat(sc);
            }
            catch(Exception ex)
            {
                JOptionPane.showMessageDialog(null, "Nhập sai định dạng!");
                txtc.selectAll();
                txtc.requestFocus();
                return;
            }
            String kq="";
            PTB2 t=new PTB2(a,b,c);
            kq=t.GiaiPT();
            txtkq.setText(kq);
        }
    });
    Container con=getContentPane();
    con.add(pnBorder);
}

// main method
public static void main(String[] args) {
        GPTB2_GUI ui=new GPTB2_GUI("Phuong trinh bac 2");
        ui.doShow();
 }
}

+ class GPTB2 -----------------------------------------------------------

package gptb2_gui;
public class PTB2 {
    float a,b,c;
    public PTB2(float a, float b, float c){
        this.a=a;
        this.b=b;
        this.c=c;
    }
    String GiaiPT(){
        String kq="";
        if(a==0)
            if(b==0)
                if(c==0)
                    kq="Phương trình vô số nghiệm";
                else
                    kq="Phương trình vô nghiệm";
            else
                kq="Phương trình có 1 nghiệm x= "+(-c/b);
        else
        {
            float d=b*b-4*a*c;
            if(d<0)
               kq="Phương trình vô nghiệm";
            if (d==0)
               kq="Phương trình có nghiệm kép x1=x2= "+(-b/(2*a)); 
            if(d>0)
            { 
                float x1=((-b-(float)Math.sqrt(d))/(2*a)), 
                      x2=((-b+(float)Math.sqrt(d))/(2*a));
                kq="x1= "+x1+"; x2= "+x2; 
            }
        }
        return kq;
    }
}

//-----------------------------------------------------------------------------------

Một số tài liệu và khoá học bổ ích dành cho bạn: 

# Tài liệu: Lập trình hướng đối tượng JAVA core dành cho người mới bắt đầu học lập trình [Click để xem]

# Khoá học online: Lập trình Java trong 4 tuần [Click để xem]


Đoc thêm các bài khác

Bài 1: Chương trình JAVA đầu tiên
Bài 2: Các kiểu dữ liệu và toán tử trong
Bài 3: Các cấu trúc điều khiển trong Java
Bài 4 : Mảng và chuỗi trong Java
Bài 5: Lớp (class) và đối tượng (object) trong Java
Bài 6:Thừa kế (Inheritance) và đa hình (Polymorphism)
Ví dụ lập trình giao diện đồ họa với Java (GUI)
Ví dụ lập trình kết nối dữ liệu với Java (JDBC)
Ví dụ về lập trình Android