Backtracking Lecture 4
Backtracking Lecture 4
class Solution
{
public int[][] ShortestDistance(int[][] mat) {
int n = mat.length;
int[][] v = new int[n][n];
boolean x = fun(mat, v, 0, 0, n);
if (x==false) {
return new int[][]{{-1}};
} else {
return v;
}
}
v[i][j] = 1;
for (int k = 1; k <= mat[i][j]; k++) {
if (fun(mat, v, i, j + k, n)) {
return true;
}
if (fun(mat, v, i + k, j, n)) {
return true;
}
}
v[i][j] = 0;
return false;
}
}
2. Find string in grid (flipkart, microsoft)
Logic is all chars have to be matched in one direction or you can say the character
matching in the rec call will be a on straight line and hence we fix the direction of
iteration in a particular dfs call and then after returning try out all the directions of
iteration , if any of the directions returns a true, we consider that cell as an answer,
break the dfs loop and continue on the next cell
class Solution {
public:
vector<vector<int>> d={{1,0},{1,1},{0,1},{-1,1},{-1,0},{-1,-1},{0,-1},{1,-1}};
bool check(int x, int y,int i,vector<vector<char>>&grid,string &word, vector<int> &v)
{
if(i==word.length()) return true;
if(x<0 or y<0 or x>=grid.size() or y>=grid[0].size() or grid[x][y]!=word[i]) return false;
return check(x+v[0],y+v[1],i+1,grid,word,v);
}
#include <bits/stdc++.h>
using namespace std;
int dx[8]={2,2,-2,-2,1,1,-1,-1};
int dy[8]={1,-1,1,-1,2,-2,2,-2};
if(move==n*n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<res[i][j]<<" ";
}
cout<<endl;
}
cout<<endl;
return;
}
res[x][y]=move;
for(int k=0;k<8;k++)
{
int nx = x+ dx[k];
int ny= y+ dy[k];
rec(nx,ny,n,res,move+1);
}
res[x][y]=0;
}
int main()
{
int n=5;
int x=2,y=0;
vector<vector<int>>res(n,vector<int>(n,0));
int move=1;
rec(x,y,n,res,move);
return 0;
}
4. Generate Parentheses (Amazon, Google, Walmart, Adobe)
if(open>closed)
{
return;
}
rec(open-1,closed,curr+"(",ans);
rec(open,closed-1,curr+")",ans);
}
vector<string> AllParenthesis(int n)
{
// Your code goes here
vector<string>ans;
string curr="";
rec(n,n,curr,ans);
return ans;
}
};
5. N Digit numbers with digits in increasing order
for(int i=last+1;i<=9;i++)
{
int a = num*10 + i;
store(a%10,n-1,a);
}
}
vector<int> increasingNumbers(int N)
{
if(N==1){
store(-1,1,0);
}
else{
store(0,N,0);
}
return v;
}
};
6. N-Queen Problem
class Solution{
public:
bool isSafe(vector<vector<int>> board, int x, int y, int n){
for(int i = 0; i<x; i++){
if(board[i][y] == 1){
return false;
}
}
row = x, col = y;
while(row >= 0 && col < n){
if(board[row][col] == 1){
return false;
}
row--;
col++;
}
return true;
}
vector<vector<int>> nQueen(int n) {
// code here
vector<vector<int>> result;
vector<vector<int>> board(n, vector<int>(n, 0));