diff --git a/Leetcode_51.java b/Leetcode_51.java new file mode 100644 index 00000000..606ae867 --- /dev/null +++ b/Leetcode_51.java @@ -0,0 +1,88 @@ +//Backtracking +//Declare a grid - n*n +//Check the possibilty by giving first row first element +//Helper recurssion start with first row first element +//It will check whether it is a valid or not +//If valid, mark as true and go to second row +//Check for the valid block. If valid go to third row and so on +//At any place where the block is not valid, backtrack. Means make that block of grid as false +//As a base case, add the path to result +//TC: n! +//SC: O( n^2 ) for the board + O( n ) recursive stack space +class Solution { + public List> solveNQueens(int n) { + List> ans=new ArrayList<>(); + boolean[][] grid=new boolean[n][n]; + helper(grid,0,ans); + return ans; + + + } + + private void helper(boolean[][] grid,int i,List> result){ + //base case + if(i==grid.length){ + List curr=new ArrayList<>(); + for(int r=0;r=0 && r=0 && c>=0){ + if(grid[r][c]==true){ + return false; + } + r-=1; + c-=1; + } + + r=i-1; + c=j+1; + while(r>=0 && c=board.length || c>=board[0].length){ + return; + } + if(board[r][c]!=word.charAt(index)) return; + + if(index==word.length()-1){ + flag=true; + return; + } + + + board[r][c]='#'; + + //actual logic + for(int[] d:dir){ + int nr=r+d[0]; + int nc=c+d[1]; + + helper(board,word,index+1,nr,nc); + + } + board[r][c]=word.charAt(index); + } +}