999 車的可用捕獲量

2022-06-07 13:24:09 字數 2655 閱讀 3964

在乙個 8 x 8 的棋盤上,有乙個白色車(rook)。也可能有空方塊,白色的象(bishop)和黑色的卒(pawn)。它們分別以字元 「r」,「.」,「b」 和 「p」 給出。大寫字元表示白棋,小寫字元表示黑棋。

車按西洋棋中的規則移動:它選擇四個基本方向中的乙個(北,東,西和南),然後朝那個方向移動,直到它選擇停止、到達棋盤的邊緣或移動到同一方格來捕獲該方格上顏色相反的卒。另外,車不能與其他友方(白色)象進入同乙個方格。

返回車能夠在一次移動中捕獲到的卒的數量。

示例 1:

輸入:

[

[".",".",".",".",".",".",".","."],

[".",".",".","p",".",".",".","."],

[".",".",".","r",".",".",".","p"],

[".",".",".",".",".",".",".","."],

[".",".",".",".",".",".",".","."],

[".",".",".","p",".",".",".","."],

[".",".",".",".",".",".",".","."],

[".",".",".",".",".",".",".","."]

]

輸出:3

解釋:在本例中,車能夠捕獲所有的卒。

示例 2:

輸入:

[

[".",".",".",".",".",".",".","."],

[".","p","p","p","p","p",".","."],

[".","p","p","b","p","p",".","."],

[".","p","b","r","b","p",".","."],

[".","p","p","b","p","p",".","."],

[".","p","p","p","p","p",".","."],

[".",".",".",".",".",".",".","."],

[".",".",".",".",".",".",".","."]

]

輸出:0

解釋:象阻止了車捕獲任何卒。

board.length == board[i].length == 8

board[i][j] 可以是 'r','.','b' 或 'p'

只有乙個格仔上存在 board[i][j] == 'r'

四種元素,r(車),b(象),p(卒),.(空)

數量,車1個,其他大於等於0個

在車的豎直或水平方向上,對沒被象擋住的卒進行求和

建立8x8矩陣,定位r座標,掃瞄r的縱軸和橫軸,返回可以直接進行r-p的座標的數量

class solution }}

// 提取r_i行和r_j列

for (int i = r_i - 1; i > -1; --i) else if (board[i][r_j] == '.') else

}for (int i = r_i + 1; i < 8; ++i) else if (board[i][r_j] == '.') else

}for (int j = r_j - 1; j > -1; --j) else if (board[r_i][j] == '.') else

}for (int j = r_j + 1; j < 8; ++j) else if (board[r_i][j] == '.') else

}return count;}};

測試**:

#include #include using namespace std;

class solution }}

// 提取r_i行和r_j列

for (int i = r_i - 1; i > -1; --i) else if (board[i][r_j] == '.') else

}for (int i = r_i + 1; i < 8; ++i) else if (board[i][r_j] == '.') else

}for (int j = r_j - 1; j > -1; --j) else if (board[r_i][j] == '.') else

}for (int j = r_j + 1; j < 8; ++j) else if (board[r_i][j] == '.') else

}return count;

}};int main() ,,,

,,,,

};solution b;

printf("%d\n", b.numrookcaptures(board));

return 0;

}

class solution ; // x軸和y軸的方向陣列控制

int dy[4] = ;

for (int i = 0; i < 8; ++i) }}

// 圈擴散

for (int i = 0; i < 4; ++i) }}

return cnt;}}

999 車的可用捕獲量

解題思路 1.先先找到r所在的位置,即獲取r所在行列座標 2.根據r所在行向左查詢p,如果遇到b,則結束。如果查詢到p則計數器加1,並結束 3.根據r所在行向右查詢p,如果遇到b,則結束。如果查詢到p則計數器加1,並結束 4.根據r所在行向上查詢p,如果遇到b,則結束。如果查詢到p則計數器加1,並結...

LeetCode999 車的可用捕獲量

解析 我想到的是一種比較笨的方法,首先遍歷找出車的位置,然後分別在同列向上,同列向下,同行向左,同行向右遍歷查詢遇到的第乙個非空位置,如果是p則加一,遍歷結束 如果是b,則遍歷結束。最後得出結果。不知道有沒有更好的方法,總感覺自己的方法太笨了,又想不出好的方法。int numrookcaptures...

LeetCode 999 車的可用捕獲量

題目 在乙個 8 x 8 的棋盤上,有乙個白色車 rook 也可能有空方塊,白色的象 bishop 和黑色的卒 pawn 它們分別以字元 r b 和 p 給出。大寫字元表示白棋,小寫字元表示黑棋。車按西洋棋中的規則移動 它選擇四個基本方向中的乙個 北,東,西和南 然後朝那個方向移動,直到它選擇停止 ...