A Tic-Tac-Toe board is given as a string array board
. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game.html
The board
is a 3 x 3 array, and consists of characters " "
, "X"
, and "O"
. The " " character represents an empty square.git
Here are the rules of Tic-Tac-Toe:github
Example 1: Input: board = ["O ", " ", " "] Output: false Explanation: The first player always plays "X". Example 2: Input: board = ["XOX", " X ", " "] Output: false Explanation: Players take turns making moves. Example 3: Input: board = ["XXX", " ", "OOO"] Output: false Example 4: Input: board = ["XOX", "O O", "XOX"] Output: true
Note:this
board
is a length-3 array of strings, where each string board[i]
has length 3.board[i][j]
is a character in the set {" ", "X", "O"}
.
這道題又是關於井字棋遊戲的,以前也有一道相似的題 Design Tic-Tac-Toe,不過那道題是模擬遊戲進行的,而這道題是讓驗證當前井字棋的遊戲狀態是否正確。這題的例子給的比較好,cover 了不少種狀況:spa
狀況一:code
0 _ _ _ _ _ _ _ _
這是不正確的狀態,由於先走的使用X,因此只出現一個O,是不對的。htm
狀況二:blog
X O X _ X _ _ _ _
這個也是不正確的,由於兩個 player 交替下棋,X最多隻能比O多一個,這裏多了兩個,確定是不對的。遊戲
狀況三:ci
X X X _ _ _ O O O
這個也是不正確的,由於一旦第一個玩家的X連成了三個,那麼遊戲立刻結束了,不會有另一個O出現。
狀況四:
X O X O _ O X O X
這個狀態沒什麼問題,是能夠出現的狀態。
好,那麼根據給的這些例子,能夠分析一下規律,根據例子1和例子2得出下棋順序是有規律的,必須是先X後O,不能破壞這個順序,那麼可使用一個 turns 變量,當是X時,turns 自增1,反之如果O,則 turns 自減1,那麼最終 turns 必定是0或者1,其餘任何值都是錯誤的,好比例子1中,turns 就是 -1,例子2中,turns 是2,都是不對的。根據例子3,能夠得出結論,只能有一個玩家獲勝,能夠用兩個變量 xwin 和 owin,來記錄兩個玩家的獲勝狀態,因爲井字棋的制勝規則是橫豎斜任意一個方向有三個連續的就算贏,那麼分別在各個方向查找3個連續的X,有的話 xwin 賦值爲 true,還要查找3個連續的O,有的話 owin 賦值爲 true,例子3中 xwin 和 owin 同時爲 true 了,是錯誤的。還有一種狀況,例子中沒有 cover 到的是:
狀況五:
X X X O O _ O _ _
這裏雖然只有 xwin 爲 true,可是這種狀態仍是錯誤的,由於一旦第三個X放下後,遊戲當即結束,不會有第三個O放下,這麼檢驗這種狀況呢?這時 turns 變量就很是的重要了,當第三個O放下後,turns 自減1,此時 turns 爲0了,而正確的應該是當 xwin 爲 true 的時候,第三個O不能放下,那麼 turns 不減1,則仍是1,這樣就能夠區分狀況五了。固然,能夠交換X和O的位置,即當 owin 爲 true 時,turns 必定要爲0。如今已經覆蓋了搜索的狀況了,參見代碼以下:
class Solution { public: bool validTicTacToe(vector<string>& board) { bool xwin = false, owin = false; vector<int> row(3), col(3); int diag = 0, antidiag = 0, turns = 0; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { if (board[i][j] == 'X') { ++row[i]; ++col[j]; ++turns; if (i == j) ++diag; if (i + j == 2) ++antidiag; } else if (board[i][j] == 'O') { --row[i]; --col[j]; --turns; if (i == j) --diag; if (i + j == 2) --antidiag; } } } xwin = row[0] == 3 || row[1] == 3 || row[2] == 3 || col[0] == 3 || col[1] == 3 || col[2] == 3 || diag == 3 || antidiag == 3; owin = row[0] == -3 || row[1] == -3 || row[2] == -3 || col[0] == -3 || col[1] == -3 || col[2] == -3 || diag == -3 || antidiag == -3; if ((xwin && turns == 0) || (owin && turns == 1)) return false; return (turns == 0 || turns == 1) && (!xwin || !owin); } };
Github 同步地址:
https://github.com/grandyang/leetcode/issues/794
相似題目:
參考資料:
https://leetcode.com/problems/valid-tic-tac-toe-state/