Conversation
N-Queens (NQueens.java)
VERDICT: PASS Word Search (WordSearch.java)Strengths:
Areas for improvement:
Here is a revised version of your code: class Solution {
int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
public boolean exist(char[][] board, String word) {
int m = board.length;
int n = board[0].length;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == word.charAt(0)) {
if (dfs(board, i, j, word, 0)) {
return true;
}
}
}
}
return false;
}
private boolean dfs(char[][] board, int i, int j, String word, int idx) {
if (idx == word.length() - 1) {
return true;
}
char temp = board[i][j];
board[i][j] = '#'; // mark as visited
for (int[] dir : dirs) {
int r = i + dir[0];
int c = j + dir[1];
if (r >= 0 && r < board.length && c >= 0 && c < board[0].length && board[r][c] == word.charAt(idx+1)) {
if (dfs(board, r, c, word, idx+1)) {
return true;
}
}
}
board[i][j] = temp; // backtrack
return false;
}
}Note: This revised code handles the one-character word by checking if we are at the last character (idx == word.length()-1) before proceeding to neighbors. Also, it uses the board itself for marking visited cells. VERDICT: NEEDS_IMPROVEMENT |
No description provided.