Back
Ma_Di_Tuan.cpp
Save
// Ma_Di_Tuan.cpp #include
using namespace std; int n; int **a; int x_offset[8] = { 2, 1, -1, -2, -2, -1, 1, 2}; int y_offset[8] = { 1, 2, 2, 1, -1, -2, -2, -1}; int dem = 1; bool Check(int x_new, int y_new) { return (x_new > 0 && x_new <= n && y_new > 0 && y_new <= n); } void Show() { cout << "Cach " << dem++ << " co cac buoc di la: " << endl; for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) cout << setw(4) << a[i][j]; cout << endl; } cout << endl; } int Try(int k, int x, int y) { if (k == n * n) { Show(); } for (int i = 0; i < 8; i++) { int x_new = x + x_offset[i]; int y_new = y + y_offset[i]; if (Check(x_new, y_new)) { if (a[x_new][y_new] == 0) { a[x_new][y_new] = k + 1; if (Try(k + 1, x_new, y_new) == 1) { return 1; } else { a[x_new][y_new] = 0; } } } } return 0; } int main() { int x, y; cout << "Nhap n: "; cin >> n; a = (int**)calloc(n + 1, sizeof(int*)); for (int i = 0; i <= n; i++) { a[i] = (int*)calloc(n + 1, sizeof(int)); } cout << "Nhap diem bat dau (x, y): "; cin >> x >> y; a[x][y] = 1; Try(1, x, y); return 0; }