Problem 61 N Queens

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 2

Day-6

Problem 61=>*N Queens*

O(n!) :: Operating Column Wise using Board (N*N)


in Each Col:: Check for all rows,where we could place
if we can place Q (using isSafe()) in the cell
Recursively call for the next Col,after placing Q.
Code:
//traverse through the rows for column 'col'
for(int i=0;i<board.size();i++)
{
if(isSafe(board,i,col))
{
board[i][col]='Q';
Solve(board,res,col+1);
//when we explore all possibilities with placing Q in that cell,mark it w/o Queen
board[i][col]='.';
}
}//return will return after 1 config is discovered for other config.
return ;

BaseCase: if col==n :print config & return(for more possible config)

isSafe:: Check for UpperDiag||LowerDiag||Left. If Q exists in any such


cell return false;

Problem 62=>*Valid Sudoku* (Link)


for any cell, if(cell==`.` || rowisValid && colIsvalid && boxisValid))
continue;
else return false

Problem 63=>Possible Bipartition {link}


Input: N = 3, dislikes = [[1,2],[1,3],[2,3]]
Output: false

Construct a graph::g[n+1][] that stores all adj.vertex for g[i]


Take a Color Arr color(n+1,-1) which can take either (0,1)
Now for i=[1,n] ,if color[i]=-1 & Dfs(i,1) is false [1 is color assigned to i]
return false; DFS(&g,src,assignedCol,&color)
else return true;if true for all i. {
color[src]=assignedCol;
for(auto &i:g[src])
{
if(color[i]==color[src])
return false;

if(color[i]==-1)
{
if(!(DFS(g,i,1-assignedCol,color)))
return false;
}
}
return true;
}

Problem 64=>* Sudoku Solver* (Link)


Here ,We operate by checking each row.but it should be performed
inside Boolean funcn s.t we can return if a no. Can be put||not.
Base Case:: Main Case::
if(row==9) //check if i could beplaced in board[row][col]
return true; for(char i='1';i<='9';i++)
if(col==9) {
return Solver(board,row+1,0); if(IsSafe(board,row,col,i))
if(board[row][col]!='.') {
return Solver(board,row,col+1); //if safe place
board[row][col]=i;
IsSafe:: //check for next cells
Check whether row is safe for char k if(Solver(board,row,col+1))
Check whether col is safe for char k return true;
}
Check whether box is safe for char k }
Here plz Note:: startR,startC is V.imp //yha phucha mtlbcan't be placed
startR=(row/3)*3 startC=(col/3)*3 board[row][col]='.';
return false;

You might also like