diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..b5b08e72 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,73 @@ +// Time Complexity : O(n * n!) +// Space Complexity : O(n^2) for the matrix + O(n) recursive stack +// Did this code successfully run on Leetcode : Yes +// Any problem you faced while coding this : No + + +// Your code here along with comments explaining your approach +//We recurse through every row and check if its safe to place the queen if yes we recursivley check for other rows and backtrack them +//When placing a queen in particular row we check for top colums in prev rows, also check diagonally top left and top right +//When all the rows are filled we check if the particular cell has a queen we convert and place it in a string as Q else as "." +class Solution { + public List> solveNQueens(int n) { + boolean [][] grid = new boolean[n][n]; + List> res = new ArrayList<>(); + backtrack(grid, 0, n, res); + return res; + } + + private void backtrack(boolean [][] grid , int r, int n, List> res) { + //base + if (r == n) {// covered all rows + //place the queens in list + List li = new ArrayList<>(); + for(int i = 0; i=0 && j >= 0) { + if(grid[i][j]) return false; //unsafe to place the queen here + i--; j--; + } + + //diagonal top right + i = r; j = c; + while(i >=0 && j < n) { + if(grid[i][j]) return false; //unsafe to place the queen here + i--; j++; + } + return true; + } +} diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..8698efa9 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,49 @@ +// Time Complexity : O(m*n*3^L) where L is the length of the word +// Space Complexity : O(n) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + + +// Your code here along with comments explaining your approach +//We perform DFS with backtracking we start with the cell whose character matches the first letter of word +//we recursively check for all its neighbors in right, top, left and down and also backtrack if no valid path found +class Solution { + public boolean exist(char[][] board, String word) { + int m = board.length; + int n = board[0].length; + int [][] dirs = {{1,0}, {-1,0}, {0,1}, {0,-1}}; + for(int i = 0; i < m; i++) { + for(int j = 0; j = board.length || j >= board[0].length || board[i][j] == '#') return false; + + //logic + if(board[i][j] == word.charAt(idx)) { + //only then you proceed + board[i][j] = '#'; //visited + //iterate over the neighbours + for(int[] dir: dirs) { + int nr = dir[0] + i; + int nc = dir[1] + j; + if(backtrack(board, word, nr, nc, idx + 1, dirs)) return true; + } + //backtrack + board[i][j] = word.charAt(idx); + } + return false; + } +}