0% found this document useful (0 votes)
20 views

Nqueen

Uploaded by

kpakshaya2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Nqueen

Uploaded by

kpakshaya2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

2.

Design a program to find all occurrences of a pattern within a text string using a brute
force approach. Your algorithm should return a list of starting indices for each occurrence
of the pattern in the text.

Example:

● Text: "abracadabra"

● Pattern: "abra"

BRUTE FORCE ALGORITHM:

 Brute Force is a straightforward method.


 It is used in algorithmic problem-solving that checks every possible solution until the
correct one is found.
 In the context of pattern matching within a text string, the brute force algorithm involves
checking every position in the text string for a match with the pattern.

In this above tree, backtracking which uses Depth-First search, considers the below states only
when the state provides a feasible solution. Consider the above tree, start from the root node,
then move to node A and then node C.

If node C does not provide the feasible solution, then there is no point in considering the states G
and H. We backtrack from node C to node A. Then, we move from node A to node D. Since
node D does not provide the feasible solution, we discard this state and backtrack from node D to
node A.
We move to node B, then we move from node B to node E. We move from node E to node K;
Since k is a solution, it takes 10 steps to find the solution. In this way, we eliminate more states
in a single iteration. Therefore, we can say that backtracking is faster and more efficient than the
brute force approach.

EXAMPLE:

If there is a lock of 4-digit PIN. The digits to be chosen from 0-9 then the brute force will be
trying all possible combinations one by one like 0001, 0002, 0003, 0004, and so on until we get
the right PIN. In the worst case, it will take 10,000 tries to find the right combination.

Some of the examples for Brute Force Algorithm:

1. Sequential search
2. String matching algorithm
3. Travelling salesman problem
4. Knapsack problem

Program for all occurrences of a pattern within a text string using a Brute Force
Approach:

#include <stdio.h>

#include <string.h>

// Function to find all occurrences of a pattern within a text string

void findOccurrences(char text[], char pattern[]) {

int n = strlen(text);

int m = strlen(pattern);

// Iterate over the text string

for (int i = 0; i <= n - m; i++) {

int j;

// Check if the current substring matches the pattern


for (j = 0; j < m; j++) {

if (text[i + j] != pattern[j])

break;

// If all characters of the pattern match, print the starting index

if (j == m) {

printf("Pattern found at index %d\n", i);

}
}

int main() {

char text[] = "abracadabra";

char pattern[] = "abra";

printf("Text: %s\n", text);

printf("Pattern: %s\n", pattern);

printf("Occurrences:\n");

findOccurrences(text, pattern);

return 0;

OUTPUT:

Text: abracadabra

Pattern: abra
Occurrences:

Pattern found at index 0

Pattern found at index 7

ALGORITHM:

STEP 1: Start at the beginning of the text string.

STEP2: For each position in the text string, compare the characters with the pattern starting from
that position.

STEP 3: If a mismatch is found at any position, move to the next position in the text string.

STEP 4: If all characters in the pattern match the corresponding characters in the text string
starting from a position, record that position as an occurrence of the pattern.

STEP 5: Repeat this process until the entire text string has been checked.

ADVANTAGES:

 Simple to implement and understand.


 Guarantees finding the optimal solution.
 Suitable for small problem instances.

DISADVANTAGES:

 Inefficient for large problem sizes due to the exponential growth in computation time.
 Not suitable for complex problems with a large search space.
 Can be resource-intensive and slow.

FEATURES:

Exhaustive search: The brute force approach systematically tries all possible solutions.
Guarantees solution: It ensures finding the correct solution given enough time and resources.

Simplicity: Easy to implement and understand, making it accessible for various problems.

Applicability: Can be used in different domains like cryptography, network security,


optimization, and data recovery.

Effectiveness for small instances: Particularly useful for manageable problem sizes where all
solutions can be explored.

1. Exhaustive search: The brute force approach systematically tries a

APPLICATION:

 Password cracking.
 Cryptanalysis.
 Combinatorial optimization problems.
 Network security testing.

3.Implement a backtracking algorithm to solve the N-Queens problem for a given N. Given
an N x N chessboard, the task is to place N queens on the board such that no two queens
attack each other. Your algorithm should return all possible solutions to the problem.

N-QUEENS PROBLEM:

The N Queen is the problem of placing N chess queens on an N×N chessboard so that no two
queens attack each other.

BACK TRACKING ALGORITHM TO SOLVE THE N-QUEENS PROBLEM:

 The backtracking algorithm works by placing queens one by one in different columns,
and then checking if the current placement is safe or not.
 If a safe placement is found, the algorithm continues to place the next queen.
 If not, it backtracks and tries a different place of the location of the chess board.
 This process continues until all queens are placed on the board without attacking each
other.

Step 0: Initialize a 4×4 board.


 It consists of 4 rows and 4 columns.
 It consists of 4 queens such as Q1, Q2, Q3 and Q4.
Step 1:
 Put our first Queen (Q1) in the (0,0) cell .
 ‘x‘ represents the cells which is not safe i.e. they are under attack by the Queen
(Q1).
 After this move to the next row [ 0 -> 1 ].

Step 2:
 Put our next Queen (Q2) in the (1,2) cell .
 After this move to the next row [ 1 -> 2 ].

Step 3:
 At row 2 there is no cell which are safe to place Queen (Q3) .
 So, backtrack and remove queen Q2 queen from cell ( 1, 2 ) .
Step 4:
 There is still a safe cell in the row 1 i.e. cell ( 1, 3 ).
 Put Queen ( Q2 ) at cell ( 1, 3).

Step 5:
 Put queen ( Q3 ) at cell ( 2, 1 ).
Step 6:
 There is no any cell to place Queen ( Q4 ) at row 3.
 Backtrack and remove Queen ( Q3 ) from row 2.
 Again there is no other safe cell in row 2, So backtrack again and remove queen
( Q2 ) from row 1.
 Queen ( Q1 ) will be remove from cell (0,0) and move to next safe cell i.e. (0 , 1).
Step 7:
 Place Queen Q1 at cell (0 , 1), and move to next row.

Step 8:
 Place Queen Q2 at cell (1 , 3), and move to next row.
Step 9:
 Place Queen Q3 at cell (2 , 0), and move to next row.

Step 10:
 Place Queen Q4 at cell (3 , 2), and move to next row.
 This is one possible configuration of solution
ALGORITHM:
STEP 1: Start with an empty N x N chessboard.
STEP 2: Place a queen in the first row of the board.
STEP 3: Move to the next row and place a queen in a safe position where it does not attack any
other queens.
STEP 4: Repeat step 3 for all rows until all N queens are placed on the board.
STEP 5: If all queens are placed successfully, add the current configuration to the list of
solutions.
STEP 6: Backtrack and try different positions if a conflict is encountered.

PROGRAM:
#include <stdio.h>
#include <stdbool.h>
#define N 4// Define the size of the chessboard
// Function to check if a queen can be placed at board[row][col]
bool isSafe(int board[N][N], int row, int col) {
int i, j;

// Check for queens in the same column


for (i = 0; i < row; i++)
if (board[i][col])
return false;

// Check for queens in the upper left diagonal


for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
if (board[i][j])
return false;
// Check for queens in the upper right diagonal
for (i = row, j = col; i >= 0 && j < N; i--, j++)
if (board[i][j])
return false;

return true; // Queen can be placed at board[row][col]


}

// Function to solve the N-Queens problem using backtracking


bools solve N Queens Util(int board[N][N], int row) {
// Base case: All queens are placed
if (row == N) {
// Print the solution
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++)
printf("%d ", board[i][j]);
printf("\n");
}
printf("\n");
return true;
}

bool res = false;


for (int col = 0; col < N; col++) {
// Check if queen can be placed at board[row][col]
if (isSafe(board, row, col)) {
// Place the queen
board[row][col] = 1;

// Recur to place rest of the queens


res = solveNQueensUtil(board, row + 1) || res;

// Backtrack and remove the queen


board[row][col] = 0;
}
}

return res;
}
// Function to solve the N-Queens problem
voids solve N Queens () {
int board[N][N] = {0};

if (! solve N QueensUtil(board, 0))


printf("No solution exists\n");
}

int main () {
printf("Solutions to the 4-Queens problem:\n");
solveNQueens();
return 0;
}
OUTPUT:
The output for the 4-Queens problem should display the solutions where queens can be placed on
the chessboard without attacking each other. The program uses backtracking to find all possible
solutions to the N-Queens problem.

You might also like