Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions Leetcode_51.java
Original file line number Diff line number Diff line change
@@ -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<List<String>> solveNQueens(int n) {
List<List<String>> ans=new ArrayList<>();
boolean[][] grid=new boolean[n][n];
helper(grid,0,ans);
return ans;


}

private void helper(boolean[][] grid,int i,List<List<String>> result){
//base case
if(i==grid.length){
List<String> curr=new ArrayList<>();
for(int r=0;r<grid.length;r++){
StringBuilder sb=new StringBuilder();
for(int c=0;c<grid[0].length;c++){
if(grid[r][c]==true){
sb.append('Q');
}else{
sb.append('.');
}
}
curr.add(sb.toString());
}
result.add(curr);
return;
}


//actual logic
for(int j=0;j<grid.length;j++){
if(isValid(grid,i,j)){
grid[i][j]=true;
helper(grid,i+1,result);
grid[i][j]=false;

}

}
}

private boolean isValid(boolean[][] grid,int i,int j){
int r=0;
while(r>=0 && r<i){
if(grid[r][j]==true){
return false;
}
r+=1;
}

r=i-1;
int c=j-1;

while(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<grid.length){
if(grid[r][c]==true){
return false;
}
r-=1;
c+=1;
}

return true;


}
}
54 changes: 54 additions & 0 deletions Leetcode_79.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//Have a dir array
//Call helper from every index
//In helper - check all neighbour blocks with index array
//If mataches with word characters - return true
//TC: O(m * n * 4^L) where L = word.length()
//SC: O(d)


class Solution {
int[][] dir;
boolean flag;
public boolean exist(char[][] board, String word) {
this.dir=new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
this.flag=false;
for(int i=0;i<board.length;i++){
for(int j=0;j<board[0].length;j++){
if (flag) return true;
helper(board,word,0,i,j);
}
}

return flag;



}
private void helper(char[][] board,String word, int index, int r, int c){
if(flag) return;

//base logic
if(r<0 || c<0 || r>=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);
}
}