Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Xay dung code giai bai toan ma di tuan
- // Khai bao cac ham thu vien
- #include <iostream>
- #include <iomanip>
- using namespace std;
- #define M 8
- // Khoi tao cho ban co
- void Init(int a[][M])
- {
- for (int i = 0; i<M; i++)
- for (int j = 0; j<M; j++)
- a[i][j] = 0;
- }
- // Kiem tra con ma di dung tren ban co
- int check(int i, int j)
- {
- return (i >= 0 && i<M && j >= 0 && j<M);
- }
- // Hien thi cac vi tri con ma di tren ban co
- void Show(int a[][M])
- {
- for (int i = 0; i<M; i++)
- {
- for (int j = 0; j < M; j++)
- cout << setw(3) << a[i][j];
- cout << endl;
- }
- }
- // Neu vi tri da di thi se khong di lai nua
- void Try(int step, int i, int j, int a[][M], int *I, int *J, int &OK)
- {
- int m, inext, jnext;
- for (m = 0; m<8; m++)
- {
- inext = i + I[m];
- jnext = j + J[m];
- if (check(inext, jnext) && a[inext][jnext] == 0)
- {
- a[inext][jnext] = step + 1;
- if (step == M*M - 1)//hoan tat
- OK = 1;
- else
- {
- Try(step + 1, inext, jnext, a, I, J, OK);
- if (!OK)
- a[inext][jnext] = 0;
- }
- }
- }
- }
- // Chuong trinh chinh
- void main()
- {
- int a[M][M], OK = 0, i = 0, j = 0;
- int I[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
- int J[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
- Init(a);
- a[i][j] = 1;
- Try(1, i, j, a, I, J, OK);
- if (OK) Show(a);
- else
- cout << "K co loi giai!" << endl;
- }
- //NHan Ctrl + F7 de bien dich chuong trinh
- // Nhan Ctrl + F5 de chay
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement