检查共享行,列,对角线的最有效方法?

时间:2015-06-27 02:42:01

标签: c++ multidimensional-array

在C ++中,如果我有一个像这样填充的正方形数组int board[8][8]

0  0  1  0  0  0  0  0 
0  0  0  0  0  1  0  0 
0  0  0  1  0  0  0  0 
1  0  0  0  0  0  0  0 
0  0  0  0  0  0  0  1 
0  0  0  0  1  0  0  0 
0  0  0  0  0  0  1  0 
0  1  0  0  0  0  0  0 

检查1中的任何一个是否与另一个1共用行,列或对角线的最短方法是什么?

编辑:当我真的意味着最短的

时,我说效率最高

2 个答案:

答案 0 :(得分:1)

You can use a bitmask for the rows, columns and diagonals to indicate if there is a 1 on any of them:

int rowMask = 0;
int ColumnMask = 0;
int diagonalMask0 = 0;
int diagonalMask1 = 0;
for(int i = 0; i < 8; i++)
{
    for(int j = 0; j < 8; j++)
    {
        if(board[i][j])
        {
            // test row:
            if(rowMask & (1 << i))
                return true;
            rowMask |= 1 << i; // mark row set

            // test column:
            if(columnMask & (1 << j))
                return true;
            columnMask |= 1 << j; // mark column set

            // test first diagonal:
            if(diagonalMask0 & (1 << (i + j)))
                return true;
            diagonalMask0 |= 1 << (i + j); // mark diagonal set

            // test first diagonal:
            if(diagonalMask1 & (1 << (8 + i - j)))
                return true;
            diagonalMask1 |= 1 << (8 + i - j); // mark diagonal set
        }
    }
}
return false;

If there is an element set in a particular row, the bit for that row is tested in rowMask. If it is already set then return true, otherwise set it using a bitwise OR so other elements can be tested against it. Do likewise for columns and the diagonals.

答案 1 :(得分:1)

8 x 8板?这必须与国际象棋有关。

这里有一个聪明的方法来测试任何一件作品是否被女王击中(即几乎与1分享一行,一列或对角线与另一张1)。

bool CG_queen::move(File f_to, Rank r_to, File f_from, Rank r_from)
{
    bool canMakeMove = false;

    //Check to see if Queen is moving only by File or only by Rank.
    //aka, only vertically or horizontally.
    if ( f_from == f_to || r_from == r_to )
    {
        canMakeMove = true;
    }

    //Check to see if Queen only moves diagonally.
    if ( abs(f_from - f_to) == abs(r_to - r_from) )
    {
        canMakeMove = true;
    }

    return canMakeMove;
}