问题:
给定一个大小为N × N的矩阵M(方阵),我如何找到任何元素的“主”和“次”对角线?
示例:
M =
| A00 A01 A02 A03 A04 |
| A10 A11 A12 A13 A14 |
| A20 A21 A22 A23 A24 |
| A30 A31 A32 A33 A34 |
>>PICKED: A21
'Main' diag: A10, A21, A32
'Secondary' diag: A03, A12, A21, A31
上下文:
我正在用Java解决八皇后问题。首先,在进行启发式之前,我已经做了以下方法:public boolean anyAtTheSameRow(Queen... queens)
public boolean anyAtTheSameCol(Queen... queens)
public boolean anyAtTheSameDiagonal(ChessBoard board, Queen... queens) {
//How it will be done: (MY THOUGHTS)
//1. Take the first queen.
//2. Get all of it's diagonal houses. "\"(main) diagonal and "/"(secondary) diagonal.
//3. Check if the next queens current row and current col are inserted in any of these pos.
//4. If any queen is inserted in the diagonal houses, then at least 1 queen can attack another. Will immediatly return true.
//5. If, after all iterations, no queen was found at the queen[0] diagonal, then will return false. No attacks are possible.
一个重要的方法是,女巫将所有这些放在一起:
public boolean canAttackAny(ChessBoard board, Queen... queens) {
return anyAtTheSameRow(queens) || anyAtTheSameCol(queens) || anyAtTheSameDiagonal(board, queens);
}
我将要做的是一个循环,从对角线的第一行开始(变量起点),然后存储下一个位置{x,y}的值,从上到下。
我尝试过的:
对于主对角线,我通过一个反复试验的过程,找到了任何元素的这种模式:
Starting point =
{0, j-i} if i < j
{i-j, 0} if i > j
{0, 0} if i = j
但是第二条对角线我没有找到任何规律我需要帮助。
我希望我解决部分八皇后问题的想法也是正确的。
1条答案
按热度按时间bprjcwpo1#
我建议第二对角线采用以下模式:
循环是
i--
和j++
,条件是i和j都保持在0到〈N的范围内