Advertisement
nguyenhappy92

Mã đi tuần với bàn cờ nxn

Nov 10th, 2015
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.33 KB | None | 0 0
  1. // Ma di tuan voi n ban co
  2. // Khai bao cac ham thu vien neu co
  3. #include <iostream>
  4. #include <iomanip>
  5. using namespace std;
  6. // Khoi tao cac gia tri ban dau
  7. int p[8] = { -2, -2, -1, -1, 1, 1, 2, 2 };
  8. int q[8] = { -1, 1, -2, 2, -2, 2, -1, 1 };
  9. int d = 0, x, y, n, a[50][50];
  10. void inkq();
  11. void tim(int x, int y, int k);
  12. // Ham chinh chuong trinh
  13. int main()
  14. {
  15. cout << "Nhap KT: ";// nhap kich thuoc
  16. cin >> n;
  17. x = 0;
  18. y = 0;
  19. for (int i = 0; i<n; i++)
  20. for (int j = 0; j<n; j++)
  21. a[i][j] = 0;
  22. a[x][y] = 1;
  23. tim(x, y, 2);
  24. if (d == 0)
  25. cout << " K giai duoc!" << endl;
  26. else
  27. cout << " Co tat ca " << d << " cach" << endl;
  28. return 0;
  29. }
  30. // In ket qua tim duoc cac buoc di cua chuong trinh
  31. void inkq()
  32. {
  33. cout << endl << " #" << ++d << "" << endl;
  34. for (int i = 0; i<n; i++)
  35. {
  36. for (int j = 0; j < n; j++)
  37. cout << setw(3) << a[i][j];
  38. cout << endl;
  39. }
  40. cout << endl;
  41. }
  42. // Thuat toan tim duong di
  43. void tim(int x, int y, int k)
  44. {
  45. if (k>n*n)
  46. inkq();
  47. else
  48. for (int i = 0; i<8; i++)
  49. {
  50. int x1 = x + p[i], y1 = y + q[i];
  51. if (x1 >= 0 && x1<n && y1 >= 0 && y1<n)
  52. if (a[x1][y1] == 0)
  53. {
  54. a[x1][y1] = k;
  55. tim(x1, y1, k + 1);
  56. a[x1][y1] = 0;
  57. }
  58. }
  59. }
  60. // Nhan Ctrl + F7 de bien dich chuong trinh
  61. // Nhan Ctrl + F5 de chay chuong trinh
  62. // no se liet ke cac truong hop ma chuong trinh se chay
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement