From 9a68bbf5a46a82afd30c87e873fbdea226480922 Mon Sep 17 00:00:00 2001 From: Pranav Sorte Date: Fri, 26 Dec 2025 10:15:37 +0530 Subject: [PATCH] done --- Problem1.java | 87 +++++++++++++++++++++++++++++++++++++++++++++++++++ Problem2.java | 56 +++++++++++++++++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 Problem1.java create mode 100644 Problem2.java diff --git a/Problem1.java b/Problem1.java new file mode 100644 index 00000000..c34a9ab2 --- /dev/null +++ b/Problem1.java @@ -0,0 +1,87 @@ +//TC - O(n! * n) +//SC - O(n^2) + O(n) + +/* +We place one queen in each row and try all possible columns using backtracking, moving to the next row only when a safe position is found. +Before placing a queen, we check the column and both upper diagonals to ensure it does not conflict with previously placed queens. +The board is updated in place and restored during backtracking, while recursion proceeds row by row until a valid arrangement is formed. +*/ + + +import java.util.ArrayList; +import java.util.List; + +public class Problem1 { + List> res; + public List> solveNQueens(int n) { + res = new ArrayList<>(); + boolean[][] board = new boolean[n][n]; + helper(board, 0); + return res; + } + + private void helper(boolean[][] board, int row) { + //base + if(row == board.length) { + List li = new ArrayList<>(); + for(int i = 0;i= 0 && j < board[i].length) { + if(board[i][j]) { + return false; + } + i--; + j++; + } + + //diagonal up left + i = row; + j = col; + while(i >= 0 && j >=0) { + if(board[i][j]) { + return false; + } + i--; + j--; + } + + return true; + } +} \ No newline at end of file diff --git a/Problem2.java b/Problem2.java new file mode 100644 index 00000000..e582b091 --- /dev/null +++ b/Problem2.java @@ -0,0 +1,56 @@ +//TC - O(m * n * 3 ^ L) +//SC - O(L) ~ recursion stck space + +/* +We scan the entire board and start a DFS from any cell that matches the first character of the word. +From each starting cell, the DFS tries all possible paths by moving in four directions while matching characters and backtracking when a path fails. +This exploration continues until the full word is matched or all possible paths from that cell are exhausted. +*/ + +public class Problem2 { + int[][] dirs = {{0,1}, {0,-1}, {1,0}, {-1,0}}; + public boolean exist(char[][] board, String word) { + int m = board.length; + int n = board[0].length; + + for(int i = 0;i= board.length || col >= board[row].length || board[row][col] != word.charAt(idx)) { + return false; + } + + + char ch = board[row][col]; + board[row][col] = '$'; + + for(int[] dir : dirs) { + int nr = row + dir[0]; + int nc = col + dir[1]; + + if(isExists(board, word, nr, nc, idx+1)) { + return true; + } + } + + board[row][col] = ch; + return false; + + } +}