diff --git a/problem1.cpp b/problem1.cpp new file mode 100644 index 00000000..c35c64fe --- /dev/null +++ b/problem1.cpp @@ -0,0 +1,60 @@ +// Time Complexity : O(n!) +// Space Complexity : O(n^2) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + + +// Your code here along with comments explaining your approach +// Start with row 1 and go upto nth row +// For each cell, try placing a queen after checking there are no queens in the same col or the diagonals +// Backtrack after placing the queen to check other valid configurations + +class Solution { +private: + bool isValid(int row, int col, int n, vector& currState) { + // check column + for(int i=row-1; i>=0; i--) { + if(currState[i][col] == 'Q') return false; + } + + // check diag - up - right + int i = row-1; int j = col+1; + while(i >=0 && j < n) { + if(currState[i][j] == 'Q') return false; + i--; + j++; + } + // check diag - up - left + i = row-1; j = col-1; + while(i >= 0 && j >= 0) { + if(currState[i][j] == 'Q') return false; + i--; + j--; + } + + return true; + } + void helper(int row, int n, vector& currState, vector>& valid) { + if(row == n) { + valid.push_back(currState); + return; + } + string currRow(n, '.'); + for(int i=0; i> solveNQueens(int n) { + vector currState; + vector> valid; + helper(0, n, currState, valid); + return valid; + } +}; \ No newline at end of file diff --git a/problem2.cpp b/problem2.cpp new file mode 100644 index 00000000..cc55b9e5 --- /dev/null +++ b/problem2.cpp @@ -0,0 +1,47 @@ +// Time Complexity : O(m*n*4^L), L = length of word +// Space Complexity : O(L) +// Did this code successfully run on Leetcode : yes +// Any problem you faced while coding this : no + + +// Your code here along with comments explaining your approach +// Start DFS from cells which have the starting char of the word +// Explore valid cells in all 4 directions, use a # symbol to mark a cell as visited +// Backtrack # to unmark as visited once that path has been explored + +class Solution { +private: + vector> dirs = {{0,1},{0,-1},{1,0},{-1,0}}; + void dfs(int r, int c, int m, int n, vector>& board, int idx, string word, bool& flag) { + if(idx == word.length()) { + flag = true; + return; + } + if(flag) return; + for(auto& dir : dirs) { + int nr = r + dir[0]; int nc = c + dir[1]; + if(nr >= 0 && nr < m && nc >= 0 && nc < n && board[nr][nc] == word[idx] && board[nr][nc] != '#') { + board[nr][nc] = '#'; + dfs(nr, nc, m, n, board, idx+1, word, flag); + board[nr][nc] = word[idx]; + } + } + } +public: + bool exist(vector>& board, string word) { + int m = board.size(); + int n = board[0].size(); + bool flag = false; + for(int i=0; i