NxN棋盘有如下特性:
**1. 对角线的数学特性**
(1) 主对角线(左上->右下):
同一主对角线上的所有格子满足 `行号 - 列号 = 常数`。 也就是说同一主对角线上所有节点的 `行号 - 列号`相等。
同一主对角线上的格子满足 `列号 - 行号 = 常数`。 也就是说同一主对角线上所有节点的 `列号 - 行号`相等。
(2) 副对角线(右上->左下):
同一副对角线上的所有格子满足 `行号 + 列号 = 常数`。 也就是说同一副对角线上所有节点`行号 + 列号`相等。
实例代码:
通过主副对角线的特性作为判断条件,打印出输入的棋盘的某个点的主副对角线。
cpp
#include <iostream>
#include <vector>
using namespace std;
// 打印一个n x n 的棋盘
void ChessBoardPrint(int n)
{
cout << endl;
for (int row = 0; row < n; ++row) {
for (int col = 0; col < n; ++col) {
cout << "*" << " ";
}
cout << endl;
}
cout << endl;
}
// 打印输入点的主副对角线
void DiagPrint1(int n, int row, int col)
{
cout << endl;
cout << endl << "method 1 : " << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (i - j == row - col) {
// 主对角线特性是这条线上的所有节点(行号 - 列号)相等
// 打印主对角线"\"是需要使用"\\ "
// cout << "\\ " << " " ;
cout << "*" << " " ;
} else if (i + j == row + col) {
// 副对角线特性是这条线上的所有节点(行号 + 列号)相等
cout << "*" << " ";
} else {
cout << "-" << " ";
}
}
cout << endl;
}
cout << endl;
}
void DiagPrint2(int n, int row, int col)
{
cout << endl << "method 2 : " << endl;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
if (j - i == col - row) {
cout << "*" << " ";
} else if (i + j == row + col) {
cout << "*" << " ";
} else {
cout << "-" << " ";
}
}
cout << endl;
}
cout << endl;
}
int main()
{
int n = 0;
cout << "输入一个棋盘的大小(n x n) : ";
cin >> n;
ChessBoardPrint(n);
int row = 0, col = 0;
cout << "输入需要查看对角线的某个点(row, col) : ";
while (cin >> row >> col) {
DiagPrint1(n, row, col);
DiagPrint2(n, row, col);
cout << "输入需要查看对角线的某个点(row, col) :";
}
return 0;
}
测试一下:输入棋盘大小,然后输入需要查看的某个点的对角线,主副对角线就根据对角线特性打印出来了。
