Skip to content

Commit 089faae

Browse files
ValidSudoku
1 parent 85198e1 commit 089faae

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.examplehub.leetcode.middle;
2+
3+
/**
4+
* https://leetcode.com/problems/valid-sudoku/
5+
*/
6+
public class ValidSudoku {
7+
public static boolean solution1(char[][] board) {
8+
9+
//travel all rows to check
10+
for (int i = 0; i < 9; i++) {
11+
int[] digitTable = new int[10];
12+
for (int j = 0; j < 9; j++) {
13+
if (board[i][j] != '.') {
14+
digitTable[board[i][j] - '0']++;
15+
}
16+
}
17+
if (containsRepeat(digitTable)) {
18+
return false;
19+
}
20+
}
21+
22+
//travel all columns to check
23+
for (int i = 0; i < 9; i++) {
24+
int[] digitTable = new int[10];
25+
for (int j = 0; j < 9; j++) {
26+
if (board[j][i] != '.') {
27+
digitTable[board[j][i] - '0']++;
28+
}
29+
}
30+
if (containsRepeat(digitTable)) {
31+
return false;
32+
}
33+
}
34+
35+
//travel all sub-box
36+
//TODO
37+
return true;
38+
}
39+
40+
public static boolean containsRepeat(int[] table) {
41+
for (int num : table) {
42+
if (num > 1) {
43+
return true;
44+
}
45+
}
46+
return false;
47+
}
48+
49+
public static boolean solution2(char[][] board) {
50+
int[][] rows = new int[9][9];
51+
int[][] cols = new int[9][9];
52+
int[][][] subBoxes = new int[3][3][9];
53+
for (int i = 0; i < 9; ++i) {
54+
for (int j = 0; j < 9; ++j) {
55+
if (board[i][j] != '.') {
56+
int index = board[i][j] - '1';
57+
rows[i][index]++;
58+
cols[j][index]++;
59+
subBoxes[i / 3][j / 3][index]++;
60+
if (rows[i][index] > 1 || cols[j][index] > 1 || subBoxes[i / 3][j / 3][index] > 1) {
61+
return false;
62+
}
63+
}
64+
}
65+
}
66+
return true;
67+
}
68+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy