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
44 changes: 44 additions & 0 deletions C++/N-queens.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
vector<vector<string>> result;

void solve(int n, int row, vector<string> &board,
vector<bool> &cols, vector<bool> &d1, vector<bool> &d2) {
if (row == n) {
result.push_back(board);
return;
}

for (int col = 0; col < n; col++) {
if (cols[col] || d1[row - col + n - 1] || d2[row + col]) continue;

board[row][col] = 'Q';
cols[col] = d1[row - col + n - 1] = d2[row + col] = true;

solve(n, row + 1, board, cols, d1, d2);

board[row][col] = '.';
cols[col] = d1[row - col + n - 1] = d2[row + col] = false;
}
}

vector<vector<string>> solveNQueens(int n) {
vector<string> board(n, string(n, '.'));
vector<bool> cols(n), d1(2*n - 1), d2(2*n - 1);
solve(n, 0, board, cols, d1, d2);
return result;
}
};

int main() {
Solution sol;
auto ans = sol.solveNQueens(4);
for (auto &board : ans) {
for (auto &row : board)
cout << row << endl;
cout << "------" << endl;
}
}
25 changes: 25 additions & 0 deletions C++/regular-expression-matching.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#include <bits/stdc++.h>
using namespace std;

class Solution {
public:
bool isMatch(string s, string p) {
if (p.empty()) return s.empty();

bool firstMatch = (!s.empty() && (s[0] == p[0] || p[0] == '.'));

if (p.size() >= 2 && p[1] == '*') {
// Two options: skip the pattern or use it if matches
return (isMatch(s, p.substr(2)) ||
(firstMatch && isMatch(s.substr(1), p)));
}
else {
return firstMatch && isMatch(s.substr(1), p.substr(1));
}
}
};

int main() {
Solution sol;
cout << boolalpha << sol.isMatch("aab", "c*a*b") << endl; // true
}