Skip to content

Commit 1810d98

Browse files
authored
Update 0037.解数独.md
0037.解数独 java bitmap解法
1 parent fb03de4 commit 1810d98

File tree

1 file changed

+67
-1
lines changed

1 file changed

+67
-1
lines changed

problems/0037.解数独.md

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -224,7 +224,7 @@ public:
224224

225225

226226
### Java
227-
227+
解法一:
228228
```java
229229
class Solution {
230230
public void solveSudoku(char[][] board) {
@@ -291,7 +291,73 @@ class Solution {
291291
}
292292
}
293293
```
294+
解法二(bitmap标记)
295+
```
296+
class Solution{
297+
int[] rowBit = new int[9];
298+
int[] colBit = new int[9];
299+
int[] square9Bit = new int[9];
300+
301+
public void solveSudoku(char[][] board) {
302+
// 1 10 11
303+
for (int y = 0; y < board.length; y++) {
304+
for (int x = 0; x < board[y].length; x++) {
305+
int numBit = 1 << (board[y][x] - '1');
306+
rowBit[y] ^= numBit;
307+
colBit[x] ^= numBit;
308+
square9Bit[(y / 3) * 3 + x / 3] ^= numBit;
309+
}
310+
}
311+
backtrack(board, 0);
312+
}
313+
314+
public boolean backtrack(char[][] board, int n) {
315+
if (n >= 81) {
316+
return true;
317+
}
318+
319+
// 快速算出行列编号 n/9 n%9
320+
int row = n / 9;
321+
int col = n % 9;
322+
323+
if (board[row][col] != '.') {
324+
return backtrack(board, n + 1);
325+
}
326+
327+
for (char c = '1'; c <= '9'; c++) {
328+
int numBit = 1 << (c - '1');
329+
if (!isValid(numBit, row, col)) continue;
330+
{
331+
board[row][col] = c; // 当前的数字放入到数组之中,
332+
rowBit[row] ^= numBit; // 第一行rowBit[0],第一个元素eg: 1 , 0^1=1,第一个元素:4, 100^1=101,...
333+
colBit[col] ^= numBit;
334+
square9Bit[(row / 3) * 3 + col / 3] ^= numBit;
335+
}
336+
if (backtrack(board, n + 1)) return true;
337+
{
338+
board[row][col] = '.'; // 不满足条件,回退成'.'
339+
rowBit[row] &= ~numBit; // 第一行rowBit[0],第一个元素eg: 1 , 101&=~1==>101&111111110==>100
340+
colBit[col] &= ~numBit;
341+
square9Bit[(row / 3) * 3 + col / 3] &= ~numBit;
342+
}
343+
}
344+
return false;
345+
}
346+
294347
348+
boolean isValid(int numBit, int row, int col) {
349+
// 左右
350+
if ((rowBit[row] & numBit) > 0) return false;
351+
// 上下
352+
if ((colBit[col] & numBit) > 0) return false;
353+
// 9宫格: 快速算出第n个九宫格,编号[0,8] , 编号=(row / 3) * 3 + col / 3
354+
if ((square9Bit[(row / 3) * 3 + col / 3] & numBit) > 0) return false;
355+
return true;
356+
}
357+
358+
}
359+
360+
```
295361
### Python
296362

297363
```python

0 commit comments

Comments
 (0)