Advertisement
nguyenhappy92

Mã đi tuần

Nov 1st, 2015
979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. // Xay dung code giai bai toan ma di tuan
  2. // Khai bao cac ham thu vien
  3. #include <iostream>
  4. #include <iomanip>
  5. using namespace std;
  6. #define M 8
  7. // Khoi tao cho ban co
  8. void Init(int a[][M])
  9. {
  10. for (int i = 0; i<M; i++)
  11. for (int j = 0; j<M; j++)
  12. a[i][j] = 0;
  13. }
  14. // Kiem tra con ma di dung tren ban co
  15. int check(int i, int j)
  16. {
  17. return (i >= 0 && i<M && j >= 0 && j<M);
  18. }
  19. // Hien thi cac vi tri con ma di tren ban co
  20. void Show(int a[][M])
  21. {
  22. for (int i = 0; i<M; i++)
  23. {
  24. for (int j = 0; j < M; j++)
  25. cout << setw(3) << a[i][j];
  26. cout << endl;
  27. }
  28. }
  29. // Neu vi tri da di thi se khong di lai nua
  30. void Try(int step, int i, int j, int a[][M], int *I, int *J, int &OK)
  31. {
  32. int m, inext, jnext;
  33. for (m = 0; m<8; m++)
  34. {
  35. inext = i + I[m];
  36. jnext = j + J[m];
  37. if (check(inext, jnext) && a[inext][jnext] == 0)
  38. {
  39. a[inext][jnext] = step + 1;
  40. if (step == M*M - 1)//hoan tat
  41. OK = 1;
  42. else
  43. {
  44. Try(step + 1, inext, jnext, a, I, J, OK);
  45. if (!OK)
  46. a[inext][jnext] = 0;
  47. }
  48. }
  49. }
  50. }
  51. // Chuong trinh chinh
  52. void main()
  53. {
  54. int a[M][M], OK = 0, i = 0, j = 0;
  55. int I[8] = { -2, -1, 1, 2, 2, 1, -1, -2 };
  56. int J[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
  57. Init(a);
  58. a[i][j] = 1;
  59. Try(1, i, j, a, I, J, OK);
  60. if (OK) Show(a);
  61. else
  62. cout << "K co loi giai!" << endl;
  63. }
  64. //NHan Ctrl + F7 de bien dich chuong trinh
  65. // Nhan Ctrl + F5 de chay
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement