study/java #neetcode Valid Sudoku
List<Integer> list=new ArrayList<>();
Set seen = new HashSet();
board[i][j] != '.'
or board[i][j] != "."
In Java, you cannot use == or != to compare strings (or characters) directly like you do with primitive data types (e.g., integers). Instead, you should use the equals method to compare strings or characters for equality.
So, when comparing a character or string with '.'
(a character), you should use if (board[i][j] != '.')
for characters or if (!board[i][j].equals("."))
for strings.
Here's the corrected code for comparing a string:
if (!board[i][j].equals(".")) {
// Code to handle non-empty cell
}
And for comparing a character (which is what you're doing in your original code):
if (board[i][j] != '.') {
// Code to handle non-empty cell
}
Remember that in your original code, you were working with characters (char
data type), not strings (String
data type). So, using !=
to compare a character to a character literal (e.g., '.'
) is the correct way to check if a cell contains a period character.
2 D Array Length
In Java, you can get the length of a row or column in a 2D array (such as char[][] board
) using the .length
property. Here's how you can do it:
- To get the number of rows:
int numRows = board.length;
- To get the number of columns in a specific row (assuming all rows have the same length, which is typical for a Sudoku board):
int numColumns = board[0].length;
Keep in mind that the above code assumes that board
is a properly initialized 2D array. If board
is not guaranteed to have any rows or columns (i.e., it could be null
), you should add appropriate checks to handle such cases to avoid null pointer exceptions.