Bài toán Mã đi tuần (ví dụ trên c++)

#include <iostream>
#include <iomanip>

using namespace std;

// Input
int n = 8;
int x, y;

// Output
int BanCo[8][8];

int dx[] = {-2, -1, +1, +2, +2, +1, -1, -2};
int dy[] = {+1, +2, +2, +1, -1, -2, -2, -1};

void Xuat()
{
for (int i=0; i<n; i++)
{
for (int j=0; j<n; j++)
{
cout << setw(3);
cout << BanCo[i][j] << " ";
}
cout << endl;
}
cout << endl;
}

// Tim 1 trong 8 o xung quanh cua (x,y) de dat Ma
void MaDiTuan(int x, int y, int buoc)
{
if (buoc > n*n)
Xuat();
else
{
// Xet 8 o xung quanh
for (int k=0; k<8; k++)
{
int xx = x + dx[k];
int yy = y + dy[k];

// Nằm trong bang nxn11111111111111111111
if (xx>=0 && yy>=0 && xx<n && yy<n)
if (BanCo[xx][yy]==0) // Chua có Mã
{
BanCo[xx][yy] = buoc;
//Xuat();
MaDiTuan(xx, yy, buoc+1);
BanCo[xx][yy]=0;
}
}
}
}

int main()
{
// Nhap x, y
x = 7;
y = 3;
n=8;

for (int i=0; i<n; i++){
for (int j=0; j<n; j++){
BanCo[i][j]=0;
}
}

int buoc=1;
BanCo[x][y] = buoc;
MaDiTuan(x, y, buoc+1);

return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s