Leetcode題解之陣列(8)有效的數獨

2021-08-31 16:02:51 字數 2005 閱讀 5906

題目:

題目描述:

判斷乙個 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 存在, 因此這個數獨是無效的。

說明:思路:這道題自己想沒想到,想過兩個for迴圈 暴力破解 時間複雜度o(n^2);看了下別人的思路。用二維boolean型陣列來作三個狀態表:分別是行表、列表、九宮格表。int index=i/3*3+j/3  這個公式能算出 board[i][j]所在的九宮格。

都用第乙個下標作為 位置標緻。

markrow[i]  [ temp ]  從0到8表示棋盤的九行。

markrow[j]  [ temp ] 的 i 表示 0到8列。

markblock[index]  [ temp ] 的i 表示0到8號九宮格。

注意:布林陣列初始化值為false.

所以該錶開始都是false表示該位置為空。知道檢索到temp一次之後 ,將該位置設為true。如果同乙個i或j或者index 遇到過同乙個temp兩次表示數獨有問題,將該位置的指改為true ,返回false。

**:

class solution 

}return true;

}

}

Leetcode題解之字串(8) 報數

題目 題目描述 1.1 2.11 3.21 4.1211 5.111221 6.312211 7.13112221 8.1113213211 9.311312111312211被讀作 one 1 乙個一 即11。11被讀作 two 1s 兩個一 即21。21被讀作 one 2 one 1 乙個二 乙...

Leetcode題解之陣列(7)移動零

題目 題目描述 給定乙個陣列nums,編寫乙個函式將所有0移動到陣列的末尾,同時保持非零元素的相對順序。示例 輸入 0,1,0,3,12 輸出 1,3,12,0,0 說明 必須在原陣列上操作,不能拷貝額外的陣列。儘量減少操作次數。思路 解法1 用兩個指標,分別指向最開始和最結尾兩個下標。每次都比較n...

leetcode題解(陣列問題)

面試中的演算法問題,有很多並不需要複雜的資料結構支撐。就是用陣列,就能考察出很多東西了。其實,經典的排序問題,二分搜尋等等問題,就是在陣列這種最基礎的結構中處理問題的,今天主要學習常見的陣列中處理問題的方法。template intbinarysearch t arr,int n,t target ...