diff --git a/NQueens.java b/NQueens.java new file mode 100644 index 00000000..ab130009 --- /dev/null +++ b/NQueens.java @@ -0,0 +1,60 @@ +// Time Complexity: O(n!) +// Space Complexity: O(n * n) +// Ran succesfully on Leetcode: yes + +class Solution { + + List> ans = new ArrayList<>(); + boolean [] diaL; + boolean [] diaR; + boolean [] col; + + public List> solveNQueens(int n) { + diaL = new boolean[n + n]; + diaR = new boolean[n + n]; + col = new boolean[n]; + char [][] board = new char[n][n]; + // first fill the board + for(int i = 0; i < n; i++) + Arrays.fill(board[i],'.'); + helper(0, n, board); + return ans; + } + + private void helper(int r, int n, char [][] board) { + if (n == r) { + // add current board as a String to the answer and return + List res = new ArrayList<>(); + for (int i = 0; i < n; i++) { + res.add(String.valueOf(board[i])); + + } + ans.add(res); + return; + } + for (int c = 0; c < n; c++) { + // if column is valid use backtracting to fill, move to the next row and backtrack + if(isValid(r, c, n)) { + // action + board[r][c] = 'Q'; + + diaL[r - c + n] = true; + diaR[r + c] = true; + col[c] = true; + // recursion + helper(r + 1, n, board); + + // backtracking + board[r][c] = '.'; + + diaL[r - c + n] = false; + diaR[r + c] = false; + col[c] = false; + } + } + } + public boolean isValid(int r, int c, int n) { + return !(diaL[r - c + n] || diaR[r + c] || col[c]); + + } +} \ No newline at end of file diff --git a/WordSearch.java b/WordSearch.java new file mode 100644 index 00000000..36609185 --- /dev/null +++ b/WordSearch.java @@ -0,0 +1,50 @@ +// Time complexity: O(M * N * 4^L) +// Space complexity: O(M * N) +// Ran succesfully on Leetcode: yes +class Solution { + boolean ans; + int [][] dirs = new int [][] { + {0, -1}, + {1, 0}, + {0, 1}, + {-1, 0} + }; + public boolean exist(char[][] board, String word) { + boolean [][] visited = new boolean[board.length][board[0].length]; + + for (int i = 0; i < board.length; i++) { + for (int j = 0; j < board[0].length; j++) { + if(word.charAt(0) == board[i][j]) { + // mark visited + visited[i][j] = true; + // recursion + helper(board, visited, 1, i, j, word); + // backtrack + visited[i][j] = false; + } + + } + } + return ans; + + } + + private void helper(char [][] b, boolean [][] v, int idx, int i, int j, String word) { + // if ans is already true return; + if(idx == word.length() || ans) { + ans = true; + return; + } + for (int [] dir: dirs) { + int r = dir[0] + i; + int c = dir[1] + j; + // for all the directions check if character at index matches and is not visited + if(r >= 0 && r < b.length && c >=0 && c < b[0].length && b[r][c] == word.charAt(idx) && !v[r][c]) { + v[r][c] = true; + helper(b, v, idx + 1, r, c, word); + v[r][c] = false; + } + } + + } +} \ No newline at end of file