File tree Expand file tree Collapse file tree 2 files changed +117
-0
lines changed Expand file tree Collapse file tree 2 files changed +117
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < iostream>
2
+
3
+ using namespace std ;
4
+ #define N 5
5
+
6
+ void printBoard (int board[N][N]){
7
+ for (int i=0 ;i<N;i++){
8
+ for (int j=0 ;j<N;j++)
9
+ cout<<board[i][j]<<" " ;
10
+ cout<<endl;
11
+ }
12
+ }
13
+
14
+ bool isValid (int board[N][N], int row, int col){
15
+ for (int i=0 ;i<col;i++)
16
+ if (board[row][i])
17
+ return false ;
18
+
19
+ for (int i=row,j=col;i>=0 && j>=0 ;i--,j--)
20
+ if (board[i][j])
21
+ return false ;
22
+
23
+ for (int i=row,j=col;j>=0 && i<N;i++,j--)
24
+ if (board[i][j])
25
+ return false ;
26
+
27
+ return true ;
28
+ }
29
+
30
+ bool solveNQueen (int board[N][N], int col){
31
+ if (col>=N)
32
+ return true ;
33
+
34
+ for (int i=0 ;i<N;i++){
35
+ if (isValid (board, i, col)){
36
+ board[i][col] = 1 ;
37
+ if (solveNQueen (board,col+1 ))
38
+ return true ;
39
+
40
+ board[i][col] = 0 ;
41
+ }
42
+ }
43
+ return false ;
44
+ }
45
+
46
+ bool checkSolution (){
47
+ int board[N][N];
48
+ for (int i=0 ;i<N;i++)
49
+ for (int j=0 ;j<N;j++)
50
+ board[i][j] = 0 ;
51
+
52
+ if (!solveNQueen (board,0 )){
53
+ cout<<" Solution does not exist" <<endl;
54
+ return false ;
55
+ }
56
+
57
+ printBoard (board);
58
+ return true ;
59
+ }
60
+
61
+ int main (){
62
+ checkSolution ();
63
+ }
Original file line number Diff line number Diff line change
1
+ // Knuth-Patt-Morris Algorithm for pattern searching in given string
2
+
3
+
4
+ /*
5
+ txt is text and pat is the pattern to be searched
6
+ vector pos stores the end position where pattern is found
7
+ (0-based indexing)
8
+ Time Conmplexity: O(pat.length + txt.length)
9
+ */
10
+
11
+ #include < bits/stdc++.h>
12
+ using namespace std ;
13
+
14
+ vector<int > kmp (string txt, string pat)
15
+ {
16
+ string s = pat + ' $' + txt;
17
+ int n = s.length (), l = pat.length ();
18
+ vector<int > LPS (n, 0 );
19
+ int k = 0 ;
20
+
21
+ /* Building LPS Array */
22
+ for (int i = 1 ; i < n; ++i)
23
+ {
24
+ while (k > 0 && s[i] != s[k])
25
+ {
26
+ k = LPS[k-1 ];
27
+ }
28
+ if (s[i] == s[k])
29
+ ++k;
30
+ LPS[i] = k;
31
+ }
32
+ /* Searching for pattern and storing occurences in vector i.e the index where pattern ends */
33
+ vector<int > pos;
34
+ for (int i = 0 ; i < n; ++i)
35
+ {
36
+ if (LPS[i] == l)
37
+ {
38
+ pos.push_back (i-l-1 );
39
+ }
40
+ }
41
+ return pos;
42
+ }
43
+
44
+ int main ()
45
+ {
46
+ string text,pattern;
47
+ cin>>text>>pattern;
48
+ vector<int > ans=kmp (text,pattern);
49
+ for (auto y:ans)
50
+ {
51
+ cout<<y+1 <<endl;
52
+ }
53
+ return 0 ;
54
+ }
You can’t perform that action at this time.
0 commit comments