diff --git a/NQueens.java b/NQueens.java new file mode 100644 index 00000000..60da2c90 --- /dev/null +++ b/NQueens.java @@ -0,0 +1,45 @@ + +class NQueens { + int[][] dirs; + public boolean exist(char[][] board, String word) { + dirs = new int[][]{{0,1},{0,-1},{1,0},{-1,0}}; + for(int i = 0; i < board.length; i++) + { + for(int j = 0; j < board[0].length; j++) + { + if(dfsBacktrack(board, i, j, word, 0)) return true; + } + } + + return false; + } + + private boolean dfsBacktrack(char[][] board, int r, int c, String word, int idx) + { + // base + // have got all char of the word + if(idx == word.length()) return true; + // check boundry for nr and nc and also check if we hit a dead end by getting a '#' already + // visited char/grid + if(r < 0 || c < 0 || r == board.length || c == board[0].length || board[r][c] == '#') return false; + + // logic + // dfs search, idx for char of word + // backtrack if not yet found + if(board[r][c] == word.charAt(idx)) + { + // action + board[r][c] = '#'; + for(int[] dir : dirs) + { + int nr = dir[0] + r; + int nc = dir[1] + c; + // recurse + if(dfsBacktrack(board, nr, nc, word, idx+1)) return true; + } + // backtrack + board[r][c] = word.charAt(idx); + } + return false; + } +} \ No newline at end of file diff --git a/WordSearch.java b/WordSearch.java new file mode 100644 index 00000000..70960394 --- /dev/null +++ b/WordSearch.java @@ -0,0 +1,81 @@ + +class WordSearch { + List> result; + public List> solveNQueens(int n) { + result = new ArrayList<>(); + boolean[][] board = new boolean[n][n]; + solveQueensHelper(board, 0); + return result; + } + + private void solveQueensHelper(boolean[][] board, int row) + { + // base + if(row == board.length) + { + List list = new ArrayList<>(); + for(int i = 0; i < board.length; i++) + { + StringBuilder sb = new StringBuilder(); + for(int j = 0; j < board.length; j++) + { + if(board[i][j]) + { + sb.append("Q"); + } + else + { + sb.append("."); + } + } + list.add(sb.toString()); + } + result.add(list); + } + + // logic + for(int col = 0; col < board.length; col++) + { + if(isSafeToPlace(board, row, col)) + { + //action + board[row][col] = true; + // recurse + solveQueensHelper(board, row+1); + // backtrack + board[row][col] = false; + } + } + } + + private boolean isSafeToPlace(boolean[][] board, int row, int col) + { + // is safe - colum up + for(int i = 0; i < row; i++) + { + if(board[i][col]) + { + return false; + } + } + + // is safe - diagonal up right + int i = row, j = col; + while(i >= 0 && j < board.length) + { + if(board[i][j]) return false; + i--; + j++; + } + + // is safe - diagonal up left + i = row; j = col; + while(i >= 0 && j >= 0) + { + if(board[i][j]) return false; + i--; + j--; + } + return true; + } +} \ No newline at end of file