LeetCode 999 車的可用捕獲量

2022-07-16 18:45:13 字數 2776 閱讀 2884

999. 車的可用捕獲量

在乙個 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

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

示例 3:

輸入:

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

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

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

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

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

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

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

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

輸出:3

解釋:車可以捕獲位置 b5,d6 和 f5 的卒。

board.length == board[i].length == 8board[i][j]可以是'r''.''b''p'只有乙個格仔上存在board[i][j] == 'r'

這道題很無聊,一句話形容這道題目:老太太的裹腳布——又臭又長。

題目本身非常簡單,但是題目描述讓人一言難盡。

題目的意思是,棋盤中有乙個「車」,問「車」向上下左右四個方向遍歷能吃到多少個「卒」。條件是:

不能出棋盤;

遇到「象」不通;

一旦吃到「卒」了,這個方向上的遍歷就結束了。

一旦描述清楚,題目就變得非常簡單了。也懶得想了,直接簡單粗暴吧。

class solution }}

// 向左

for (int j = rookj; j >= 0; j--)

if (board[rooki][j] == 'p')

}// 向右

for (int j = rookj; j < board[rooki].length; j++)

if (board[rooki][j] == 'p')

}// 向上

for (int i = rooki; i >= 0; i--)

if (board[i][rookj] == 'p')

}// 向下

for (int i = rooki; i < board.length; i++)

if (board[i][rookj] == 'p')

}return count;}}

LeetCode999 車的可用捕獲量

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

LeetCode 999 車的可用捕獲量

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

999 車的可用捕獲量

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