有效的數獨 LeetCode 陣列的巧妙運用

2021-08-27 14:13:55 字數 1998 閱讀 9355

有效的數獨

判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。

數字1-9在每一行只能出現一次。

數字1-9在每一列只能出現一次。

數字1-9在每乙個以粗實線分隔的3x3宮內只能出現一次。

上圖是乙個部分填充的有效的數獨。

數獨部分空格內已填入了數字,空白格用'.'表示。

示例 1:

輸入:[

["5","3",".",".","7",".",".",".","."],

["6",".",".","1","9","5",".",".","."],

[".","9","8",".",".",".",".","6","."],

["8",".",".",".","6",".",".",".","3"],

["4",".",".","8",".","3",".",".","1"],

["7",".",".",".","2",".",".",".","6"],

[".","6",".",".",".",".","2","8","."],

[".",".",".","4","1","9",".",".","5"],

[".",".",".",".","8",".",".","7","9"]

]輸出:true

示例 2:

輸入:[

["8","3",".",".","7",".",".",".","."],

["6",".",".","1","9","5",".",".","."],

[".","9","8",".",".",".",".","6","."],

["8",".",".",".","6",".",".",".","3"],

["4",".",".","8",".","3",".",".","1"],

["7",".",".",".","2",".",".",".","6"],

[".","6",".",".",".",".","2","8","."],

[".",".",".","4","1","9",".",".","5"],

[".",".",".",".","8",".",".","7","9"]

]輸出:false解釋:除了第一行的第乙個數字從5改為8以外,空格內其他數字均與 示例1 相同。

但由於位於左上角的 3x3 宮內有兩個 8 存在, 因此這個數獨是無效的。

說明:題解:

今天刷了好幾道題,就這題還有點意思,主要是優化,橫縱座標的有效性沒問題直接用map搞,3x3的方格的有效性我一開始是直接寫了個check函式,在函式裡用map進行驗證,後來看見別人的**,覺得很巧妙,可以開乙個三維陣列,假設驗證第i行第j個,那麼可以把它唯一標記為p[i/3][j/3],可以驗證(0,0),(0,1)一直到(2,2)也就是第乙個方格所有座標都符合這個唯一標記,而其他的座標不符合,那麼開乙個三維陣列就可以標記整張圖的每個3x3的方格裡的有效性。我修改之後的時間居然跑得和原來的一樣。。莫名其妙

我修改前的**:

class solution 

if(board[i][j]!='.')

if(board[j][i]!='.')}}

return true;

}bool check(vector>& board,int sx,int sy)

if(board[j][i]!='.')}}

return true;}};

LeetCode陣列 有效的數獨

有效的數獨 判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。上圖是乙個部分填充的有效的數獨。數獨部分空格內已填入了數字,空白格...

leetcode 有效的數獨

判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。上圖是乙個部分填充的有效的數獨。數獨部分空格內已填入了數字,空白格用 表示。示...

LeetCode 有效的數獨(python)

題目 判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。數字 1 9 在每一行只能出現一次。數字 1 9 在每一列只能出現一次。數字 1 9 在每乙個以粗實線分隔的 3x3 宮內只能出現一次。上圖是乙個部分填充的有效的數獨 數獨部分空格內已填入了數字,空白格用 表...