0% found this document useful (0 votes)
9 views51 pages

Ilovepdf Merged

The document outlines various algorithms implemented to solve geometric problems and dynamic programming solutions. It includes pseudocode and C code for tasks such as checking rectangle overlap, calculating distances, and generating Pascal's triangle. The results demonstrate successful execution and verification of the algorithms.

Uploaded by

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

Ilovepdf Merged

The document outlines various algorithms implemented to solve geometric problems and dynamic programming solutions. It includes pseudocode and C code for tasks such as checking rectangle overlap, calculating distances, and generating Pascal's triangle. The results demonstrate successful execution and verification of the algorithms.

Uploaded by

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

23CSR405 – Advanced Algorithms

EXP.NO: 1
IMPLEMENT ALGORITHMS TO SOLVE THE GEOMETRIC PROBLEMS
DATE:

AIM:

To implement algorithms to solve the geometric problems.

PSEUDOCODE 1:

bool isRectangleOverlap(int* rec1, int rec1Size, int* rec2, int rec2Size) {

if((rec1[2]>rec2[0] & rec1[3]>rec2[1]) && (rec1[0]<rec2[2] && rec1[1]<rec2[3])){

return true;

}else{

return false;

}}

CODE 1:

#include <stdio.h>

#include<stdbool.h>

bool isRectangleOverlap(int* rec1,int* rec2) {

if((rec1[2]>rec2[0] && rec1[3]>rec2[1]) && (rec1[0]<rec2[2] && rec1[1]<rec2[3])){

return true;

}else{

return false;

}}

int main(){

int rec1[4],rec2[4];

printf("Enter the two [x,y] coordinates of rectangle1:");

for(int i=0;i<4;i++){

scanf("%d",&rec1[i]);

printf("Enter the two [x,y] coordinates of rectangle2:");

for(int i=0;i<4;i++){

scanf("%d",&rec2[i]);

717823F229
23CSR405 – Advanced Algorithms

if(isRectangleOverlap(rec1,rec2)){

printf("The two rectangle overlaps each other. ");

} else{

printf("The two rectangles doesnot overlaps each other.");

OUTPUT 1:

717823F229
23CSR405 – Advanced Algorithms

PSEUDOCODE 2:

int compare(const void* a, const void* b) {

Coordinate* c1 = (Coordinate*)a;

Coordinate* c2 = (Coordinate*)b;

// Manhattan distance formula

int dist1 = abs(c1->row - 0) + abs(c1->col - 0);

int dist2 = abs(c2->row - 0) + abs(c2->col - 0);

return dist1 - dist2;

void allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {

Coordinate coordinates[rows * cols];

int index = 0;

for (int r = 0; r < rows; r++) {

for (int c = 0; c < cols; c++) {

coordinates[index].row = r;

coordinates[index].col = c;

index++;

qsort(coordinates, rows * cols, sizeof(Coordinate), compare);

for (int i = 0; i < rows * cols; i++) {

printf("[%d, %d] ", coordinates[i].row, coordinates[i].col);

printf("\n");

CODE 2:

#include <stdio.h>

#include <stdlib.h>

typedef struct {

int row;

int col;

717823F229
23CSR405 – Advanced Algorithms

} Coordinate;

int compare(const void* a, const void* b) {

Coordinate* c1 = (Coordinate*)a;

Coordinate* c2 = (Coordinate*)b;

int dist1 = abs(c1->row - 0) + abs(c1->col - 0);

int dist2 = abs(c2->row - 0) + abs(c2->col - 0);

return dist1 - dist2;

void allCellsDistOrder(int rows, int cols, int rCenter, int cCenter) {

Coordinate coordinates[rows * cols];

int index = 0;

for (int r = 0; r < rows; r++) {

for (int c = 0; c < cols; c++) {

coordinates[index].row = r;

coordinates[index].col = c;

index++;

qsort(coordinates, rows * cols, sizeof(Coordinate), compare);

for (int i = 0; i < rows * cols; i++) {

printf("[%d, %d] ", coordinates[i].row, coordinates[i].col);

printf("\n");

int main() {

int rows,cols,rCenter,cCenter;

printf("Enter the no.of rows: ");

scanf("%d",&rows);

printf("Enter the no.of cols:");

scanf("%d",&cols);

717823F229
23CSR405 – Advanced Algorithms

printf("Enter the rCenter:");

scanf("%d",&rCenter);

printf("Enter the cCenter:");

scanf("%d",&cCenter);

allCellsDistOrder(rows, cols, rCenter, cCenter);

return 0;

OUTPUT 2:

717823F229
23CSR405 – Advanced Algorithms

PSEUDOCODE 3:

int min(int a, int b) {

return a < b ? a : b;

int max(int a, int b) {

return a > b ? a : b;

int maxSquareArea(int bottomLeft[][2], int topRight[][2], int n) {

int maxArea = 0;

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

for (int j = i + 1; j < n; j++) {

int intersectLeft = max(bottomLeft[i][0], bottomLeft[j][0]);

int intersectRight = min(topRight[i][0], topRight[j][0]);

int intersectBottom = max(bottomLeft[i][1], bottomLeft[j][1]);

int intersectTop = min(topRight[i][1], topRight[j][1]);

if (intersectLeft < intersectRight && intersectBottom < intersectTop) {

int sideLength = min(intersectRight - intersectLeft, intersectTop - intersectBottom);

if (sideLength > maxArea) {

maxArea = sideLength;

return maxArea * maxArea;

CODE 3:

#include <stdio.h>

#include <limits.h>

int min(int a, int b) {

return a < b ? a : b;

717823F229
23CSR405 – Advanced Algorithms

int max(int a, int b) {

return a > b ? a : b;

int maxSquareArea(int bottomLeft[][2], int topRight[][2], int n) {

int maxArea = 0;

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

for (int j = i + 1; j < n; j++) {

int intersectLeft = max(bottomLeft[i][0], bottomLeft[j][0]);

int intersectRight = min(topRight[i][0], topRight[j][0]);

int intersectBottom = max(bottomLeft[i][1], bottomLeft[j][1]);

int intersectTop = min(topRight[i][1], topRight[j][1]);

if (intersectLeft < intersectRight && intersectBottom < intersectTop) {

int sideLength = min(intersectRight - intersectLeft, intersectTop - intersectBottom);

if (sideLength > maxArea) {

maxArea = sideLength;

return maxArea * maxArea;

int main() {

int n;

printf("Enter the number of rectangles: ");

scanf("%d", &n);

int bottomLeft[n][2], topRight[n][2];

printf("Enter the bottom-left and top-right coordinates of the rectangles:\n");

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

scanf("%d %d %d %d", &bottomLeft[i][0], &bottomLeft[i][1], &topRight[i][0], &topRight[i][1]);

717823F229
23CSR405 – Advanced Algorithms

int result = maxSquareArea(bottomLeft, topRight, n);

printf("Maximum area of a square that can fit inside the intersecting region of at least two rectangles:
%d\n", result);

return 0;

OUTPUT 3:

717823F229
23CSR405 – Advanced Algorithms

PSEUDOCODE 4:

typedef struct {

int x;

int y;

double distance;

} Point;

int compare(const void *a, const void *b) {

Point *pointA = (Point *)a;

Point *pointB = (Point *)b;

return (pointA->distance > pointB->distance) - (pointA->distance < pointB->distance);

void kClosestPoints(int points[][2], int k, int n, int result[][2]) {

Point pointArray[n];

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

pointArray[i].x = points[i][0];

pointArray[i].y = points[i][1];

pointArray[i].distance = sqrt(points[i][0] * points[i][0] + points[i][1] * points[i][1]);

qsort(pointArray, n, sizeof(Point), compare);

for (int i = 0; i < k; i++) {

result[i][0] = pointArray[i].x;

result[i][1] = pointArray[i].y;

CODE 4:

#include <stdio.h>

#include <stdlib.h>

#include <math.h>

typedef struct {

int x;

717823F229
23CSR405 – Advanced Algorithms

int y;

double distance;

} Point;

int compare(const void *a, const void *b) {

Point *pointA = (Point *)a;

Point *pointB = (Point *)b;

return (pointA->distance > pointB->distance) - (pointA->distance < pointB->distance);

void kClosestPoints(int points[][2], int k, int n, int result[][2]) {

Point pointArray[n];

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

pointArray[i].x = points[i][0];

pointArray[i].y = points[i][1];

pointArray[i].distance = sqrt(points[i][0] * points[i][0] + points[i][1] * points[i][1]);

qsort(pointArray, n, sizeof(Point), compare);

for (int i = 0; i < k; i++) {

result[i][0] = pointArray[i].x;

result[i][1] = pointArray[i].y;

int main() {

int n, k;

printf("Enter the number of points: ");

scanf("%d", &n);

int points[n][2];

printf("Enter the coordinates of the points:\n");

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

scanf("%d %d", &points[i][0], &points[i][1]);

printf("Enter the value of k: ");

717823F229
23CSR405 – Advanced Algorithms

scanf("%d", &k);

int result[k][2];

kClosestPoints(points, k, n, result);

printf("The %d closest points to the origin are:\n", k);

for (int i = 0; i < k; i++) {

printf("[%d, %d]\n", result[i][0], result[i][1]);

return 0;

OUTPUT 4:

Marks
Criterion Max Marks
Awarded

Preparation 30

Lab
30
Performance
Viva voce and
40
performance

Total 100

Faculty Signature

RESULT:

Thus, the program to implement algorithms to solve the geometric problems was successfully
executed and the output is verified.

717823F229
23CSR405 – Advanced Algorithms

EXP.NO: 2
DEVELOP SOLUTIONS USING DYNAMIC PROGRAMMING
DATE:

AIM:

To develop solutions using dynamic programming.

PSEUDOCODE 1:

int maxRepeating(char* sequence, char* word) {

int n = strlen(sequence);

int k = strlen(word);

int dp[n+1];

memset(dp,0,sizeof(dp));

int max_k = 0;

for(int i=k;i<=n;i++){

if(strncmp(sequence + i-k,word,k)==0){

dp[i] = dp[i-k] +1;

if(dp[i]> max_k){

max_k = dp[i];

return max_k;

CODE 1:

#include <stdio.h>

#include <string.h>

int maxRepeating(char* sequence, char* word) {

int n = strlen(sequence);

int k = strlen(word);

717823F229
23CSR405 – Advanced Algorithms

int dp[n+1];

memset(dp,0,sizeof(dp));

int max_k = 0;

for(int i=k;i<=n;i++){

if(strncmp(sequence + i-k,word,k)==0){

dp[i] = dp[i-k] +1;

if(dp[i]> max_k){

max_k = dp[i];

return max_k;

int main() {

char sequence[101], word[101];

printf("Enter the sequence: ");

scanf("%s", sequence);

printf("Enter the word: ");

scanf("%s", word);

int result = maxRepeating(sequence, word);

printf("Max k-repeating value: %d\n", result);

return 0;

OUTPUT 1:

717823F229
23CSR405 – Advanced Algorithms

PSEUDOCODE 2:

void printPascal(int **triangle, int numRows) {

printf("[");

for (int i = 0; i < numRows; i++) {

printf("[");

for (int j = 0; j <= i; j++) {

printf("%d ", triangle[i][j]);

if(j!=i)

printf(",");

printf("]");

if(i!=numRows-1)

printf(",");

printf("]");

int** generatePascalTriangle(int numRows) {

int** triangle = (int**)malloc(numRows * sizeof(int*));

for (int i = 0; i < numRows; i++) {

triangle[i] = (int*)malloc((i + 1) * sizeof(int));

triangle[i][0] = 1;

triangle[i][i] = 1;

for (int j = 1; j < i; j++) {

triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];

}}

return triangle;

717823F229
23CSR405 – Advanced Algorithms

CODE 2:

#include <stdio.h>

#include <stdlib.h>

void printPascal(int **triangle, int numRows) {

printf("[");

for (int i = 0; i < numRows; i++) {

printf("[");

for (int j = 0; j <= i; j++) {

printf("%d ", triangle[i][j]);

if(j!=i)

printf(",");

printf("]");

if(i!=numRows-1)

printf(",");

printf("]");

int** generatePascalTriangle(int numRows) {

int** triangle = (int**)malloc(numRows * sizeof(int*));

for (int i = 0; i < numRows; i++) {

triangle[i] = (int*)malloc((i + 1) * sizeof(int));

triangle[i][0] = 1;

triangle[i][i] = 1;

for (int j = 1; j < i; j++) {

triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];

} }

return triangle;

int main() {

int numRows;

717823F229
23CSR405 – Advanced Algorithms

printf("Enter the number of rows: ");

scanf("%d", &numRows);

int** triangle = generatePascalTriangle(numRows);

printPascal(triangle, numRows);

for (int i = 0; i < numRows; i++) {

free(triangle[i]);

free(triangle);

return 0;

OUTPUT 2:

717823F229
23CSR405 – Advanced Algorithms

PSEUDOCODE 3:

bool isSubsequence(char *s, char *t) {

int i = 0, j = 0;

while (s[i] != '\0' && t[j] != '\0') {

if (s[i] == t[j]) {

i++;

j++;

return s[i] == '\0';

CODE 3:

#include <stdio.h>

#include <stdbool.h>

bool isSubsequence(char *s, char *t) {

int i = 0, j = 0;

while (s[i] != '\0' && t[j] != '\0') {

if (s[i] == t[j]) {

i++;

j++;

return s[i] == '\0';

int main() {

char s[101], t[10001];

printf("Enter the string s: ");

scanf("%s", s);

printf("Enter the string t: ");

scanf("%s", t);

if (isSubsequence(s, t)) {

717823F229
23CSR405 – Advanced Algorithms

printf("true\n");

} else {

printf("false\n");

return 0;

OUTPUT 3:

717823F229
23CSR405 – Advanced Algorithms

PSEUDOCODE 4:

int* countBits(int n, int* returnSize) {

int* ans = (int*)malloc((n + 1) * sizeof(int));

ans[0] = 0;

for (int i = 1; i <= n; i++) {

ans[i] = ans[i >> 1] + (i & 1);

*returnSize = n + 1;

return ans;

CODE 4:

#include <stdio.h>

#include <stdlib.h>

int* countBits(int n, int* returnSize) {

int* ans = (int*)malloc((n + 1) * sizeof(int));

ans[0] = 0;

for (int i = 1; i <= n; i++) {

ans[i] = ans[i >> 1] + (i & 1);

*returnSize = n + 1;

return ans;

int main() {

int n;

printf("Enter the value of n: ");

scanf("%d", &n);

int returnSize;

int* result = countBits(n, &returnSize);

printf("Output: [");

for (int i = 0; i < returnSize; i++) {

717823F229
23CSR405 – Advanced Algorithms

printf("%d", result[i]);

if (i < returnSize - 1) {

printf(",");

printf("]\n");

free(result);

return 0;

OUTPUT 4:

Marks
Criterion Max Marks
Awarded

Preparation 30

Lab
30
Performance
Viva voce and
40
performance

Total 100

Faculty Signature

RESULT:

Thus, the program to develop solutions using dynamic programming was successfully executed and
the output was verified.

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

Ex.No: 03
Implement algorithms using backtracking methods
Date:

AIM:
To Implement algorithms using backtracking methods.

QUESTION 1:

PSEUDO CODE:
int backTrack(vector<int>& nums, int idx, int size, int XOR) {
if (idx == size)
return XOR;
return backTrack(nums, idx + 1, size, XOR ^ nums[idx]) + backTrack(nums, idx + 1, size, XOR);
}
int subsetXORSum(vector<int>& nums) {
int n = nums.size();
return backTrack(nums, 0, n, 0);
}

SOURCE CODE:
#include <iostream>
#include <vector>
using namespace std;
int backTrack(vector<int>& nums, int idx, int size, int XOR) {
if (idx == size)
return XOR;
return backTrack(nums, idx + 1, size, XOR ^ nums[idx]) + backTrack(nums, idx + 1, size, XOR);
}
int subsetXORSum(vector<int>& nums) {
int n = nums.size();
return backTrack(nums, 0, n, 0);
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;

vector<int> nums(n);
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) {
cin >> nums[i];
}

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

cout << "Sum of all subset : " << subsetXORSum(nums) << endl;
return 0;
}
Time Complexity: O(2^n)

OUTPUT:

QUESTION 2:

PSEUDO CODE:
int solve(vector<int>&nums, vector<int>&vis, int index, int n){
if(index==n+1) return 1;
int res=0;
for(int i=0;i<nums.size();i++){
if(vis[nums[i]]==0 && (nums[i]%index==0 || index%nums[i]==0)){
vis[nums[i]]=1;
res+=solve(nums,vis,index+1,n);
vis[nums[i]]=0;
}
}
return res;
}
int countArrangement(int n) {
vector<int>nums, vis(n+1,0);
for(int i=1;i<=n;i++){
nums.push_back(i);
}

int ans=solve(nums,vis,1,n);
return ans;

SOURCE CODE:
#include<bits/stdc++.h>

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

using namespace std;


int solve(vector<int>&nums, vector<int>&vis, int index, int n){
if(index==n+1) return 1;
int res=0;
for(int i=0;i<nums.size();i++){
if(vis[nums[i]]==0 && (nums[i]%index==0 || index%nums[i]==0)){
vis[nums[i]]=1;
res+=solve(nums,vis,index+1,n);
vis[nums[i]]=0;
}
}
return res;
}
int countArrangement(int n) {
vector<int>nums, vis(n+1,0);
for(int i=1;i<=n;i++){
nums.push_back(i);
}
int ans=solve(nums,vis,1,n);
return ans;
}
int main() {
int n;
cout << "Enter the value of n: ";
cin >> n;
int result = countArrangement(n);
cout << "Number of arrangements: " << result << endl;
return 0;
}
Time Complexity: O(n!)

OUTPUT:

QUESTION 3:

PSEUDO CODE:
vector<vector<int>>ans;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

void backtrack(vector<int>&arr,int start,int rem,vector<int>&temp){


if(rem<0)return;
if(rem==0)ans.push_back(temp);
for(int i=start;i<arr.size();i++){
temp.push_back(arr[i]);
backtrack(arr,i,rem-arr[i],temp);
temp.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int>temp;
backtrack(candidates,0,target,temp);
return ans;
}

SOURCE CODE:
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>>ans;
void backtrack(vector<int>&arr,int start,int rem,vector<int>&temp){
if(rem<0)return;
if(rem==0)ans.push_back(temp);
for(int i=start;i<arr.size();i++){
temp.push_back(arr[i]);
backtrack(arr,i,rem-arr[i],temp);
temp.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<int>temp;
backtrack(candidates,0,target,temp);
return ans;
}

int main() {
int n, target;
cout << "Enter the number of candidates: ";
cin >> n;
vector<int> candidates(n);
cout << "Enter the candidates: ";
for (int i = 0; i < n; i++) {
cin >> candidates[i];
}
cout << "Enter the target: ";
cin >> target;
vector<vector<int>> result = combinationSum(candidates, target);
cout << "Combinations: ";

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

for (const auto& combination : result) {


cout << "[ ";
for (int num : combination) {
cout << num << " ";
}
cout << "] ";
}
return 0;
}
Time Complexity: O(n^t)

OUTPUT:

QUESTION 4:

PSEUDO CODE:
void solve(unordered_set<string>& S, string& result, string& curr, int& n, bool& found) {
if (found) return;
if (curr.size() == n) {
if (S.find(curr) == S.end())
result = curr;
return;
}
curr += '0';
solve(S, result, curr, n, found);
curr.pop_back();
curr += '1';
solve(S, result, curr, n, found);
curr.pop_back();
}
string findDifferentBinaryString(vector<string>& nums) {
string result = "";
string curr = "";
bool found = false;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

int n = nums[0].size();
unordered_set<string> S(nums.begin(), nums.end());
solve(S, result, curr, n, found);
return result;
}

SOURCE CODE:
#include<bits/stdc++.h>
using namespace std;
void solve(unordered_set<string>& S, string& result, string& curr, int& n, bool& found) {
if (found) return;
if (curr.size() == n) {
if (S.find(curr) == S.end())
result = curr;
return;
}
curr += '0';
solve(S, result, curr, n, found);
curr.pop_back();
curr += '1';
solve(S, result, curr, n, found);
curr.pop_back();
}
string findDifferentBinaryString(vector<string>& nums) {
string result = "";
string curr = "";
bool found = false;
int n = nums[0].size();
unordered_set<string> S(nums.begin(), nums.end());
solve(S, result, curr, n, found);
return result;
}
int main() {
int n;
cout << "Enter the number strings: ";
cin >> n;
vector<string> nums(n);
cout << "Enter binary strings :\n";
for (int i = 0; i < n; i++) {
cin >> nums[i];
}
string result = findDifferentBinaryString(nums);
cout << "A different binary string is: " << result << endl;
return 0;
}
Time Complexity: O(2^n)

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

OUTPUT:

CRITERION MAX MARKS


MARKS AWARDED
Preparation 30
Lab Performance 30
Viva voce and
completion of 40
record
Total 100
Faculty Signature

RESULT:
Thus Implement algorithms using backtracking methods was executed successfully and output was
verified.

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

Ex.No: 04
Detect cycles in a graph using appropriate algorithms.
Date:

AIM:
To Detect cycles in a graph using appropriate algorithms.

QUESTION 1:

PSEUDOCODE:
void dfs(vector<vector<char>>& grid, vector<vector<int>>& visited, int x, int y, int lastX, int lastY, char
cur, int color) {
visited[x][y] = color;
for (int i = 0; i < 4; i++) {
int a = x + dir[i];
int b = y + dir[i + 1];
if (a < 0 || b < 0 || a >= grid.size() || b >= grid[0].size()) continue;
if (!(a == lastX && b == lastY) && grid[a][b] == cur && visited[a][b] == color) {
ans = true;
}
if (visited[a][b] == 0 && !(a == lastX && b == lastY) && grid[a][b] == cur) {
dfs(grid, visited, a, b, x, y, cur, color);
}
}
}
bool containsCycle(vector<vector<char>>& grid) {
ans = false;
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> visited(m, vector<int>(n));
int color = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == 0) {
dfs(grid, visited, i, j, -1, -1, grid[i][j], color);
color++;
}
}
}
return ans;
}

SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
vector<int> dir{1, 0, -1, 0, 1};

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

bool ans=false;
void dfs(vector<vector<char>>& grid,vector<vector<int>>& visited,int x,int y,int lastX,int lastY,char
cur,int color) {
visited[x][y]=color;
for(int i=0;i<4;i++) {
int a=x+dir[i];
int b=y+dir[i + 1];
if(a<0 || b<0 || a>=grid.size() || b>=grid[0].size()) continue;
if(!(a==lastX && b==lastY) && grid[a][b]==cur && visited[a][b]==color) {
ans = true;
}
if(visited[a][b] == 0 && !(a==lastX && b==lastY) && grid[a][b]==cur) {
dfs(grid,visited,a,b,x,y,cur,color);
}
}
}
bool containsCycle(vector<vector<char>>& grid) {
ans = false;
int m = grid.size();
int n = grid[0].size();
vector<vector<int>> visited(m, vector<int>(n));
int color = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (visited[i][j] == 0) {
dfs(grid, visited, i, j, -1, -1, grid[i][j], color);
color++;
}
}
}
return ans;
}
int main() {
int m, n;
cout << "Enter number of rows: ";
cin >> m;
cout << "Enter number of columns: ";
cin >> n;
vector<vector<char>> grid(m, vector<char>(n));
cout << "Enter the grid elements row-wise:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> grid[i][j]; } }
bool result = containsCycle(grid);
cout << "Output: " << (result ? "true" : "false") << endl;
return 0;
}
Time Complexity: O(m × n)

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

OUTPUT:

QUESTION 2:

PSEUDOCODE:

bool detectCapitalUse(string word) {


if(word.size() == 1)
return true;
int upper = 0, lower = 0;
for(char ch : word){
if (islower(ch)) lower++;
else upper++;
}
if(lower==word.size() || upper==word.size()){
return true;
}
else if(upper==1 && isupper(word[0])){
return true;
}
return false;
}

SOURCE CODE:

#include <bits/stdc++.h>
using namespace std;
bool detectCapitalUse(string word) {
if(word.size() == 1)
return true;
int upper = 0, lower = 0;
for(char ch : word){
if (islower(ch)) lower++;
else upper++;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

}
if(lower==word.size() || upper==word.size()){
return true;
}
else if(upper==1 && isupper(word[0])){
return true;
}
return false;
}
int main() {
string word;
cout << "Enter a word: ";
cin >> word;
bool result = detectCapitalUse(word);
cout << "Output: " << (result ? "true" : "false") << endl;
return 0;
}
Time Complexity: O(1)

OUTPUT:

QUESTION 3:

PSEUDOCODE:

bool squareIsWhite(string cod) {


char c=cod[0];
int n=cod[1]-'0';
return (c-'a'+ 1+n)%2==1;
}

SOURCE CODE:

#include <bits/stdc++.h>
using namespace std;
bool squareIsWhite(string cod) {
char c=cod[0];
int n=cod[1]-'0';
return (c-'a'+ 1+n)%2==1;
}

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

int main() {
string cod;
cout<<"Enter the chessboard coordinates: ";
cin>>cod;
bool res=squareIsWhite(cod);
cout<<"Output: "<<(res?"true":"false")<<endl;
return 0;
}
Time Complexity: O(1)

OUTPUT:

QUESTION 4:

PSEUDO CODE:

bool hascycle(ListNode* head){


ListNode* fast=head;
ListNode* slow=head;
while(fast!=nullptr && fast->next!=nullptr){
fast=fast->next->next;
slow=slow->next;
if(fast==slow) {
return true;
}
}
return false;
}

SOURCE CODE:

#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
bool hascycle(ListNode* head){
ListNode* fast=head;
ListNode* slow=head;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

while(fast!=nullptr && fast->next!=nullptr){


fast=fast->next->next;
slow=slow->next;
if(fast==slow) {
return true;
}
}
return false;
}
ListNode* createlist(vector<int> val,int pos){
if (val.empty())
return nullptr;
ListNode* head=new ListNode(val[0]);
ListNode* tail=head;
ListNode* cycleNode=nullptr;
if(pos == 0) cycleNode=head;
for(int i=1;i<val.size();i++) {
tail->next=new ListNode(val[i]);
tail=tail->next;
if(i==pos)
cycleNode=tail;
}
if(cycleNode){
tail->next=cycleNode;
}
return head;
}
int main() {
int n,pos;
cout<<"Enter number of nodes: ";
cin>>n;
vector<int> val(n);
cout<<"Enter the values: ";
for(int i=0;i<n;i++) {
cin>>val[i];
}
cout<<"Enter cycle position(-1 for no cycle): ";
cin>>pos;
ListNode* head=createlist(val, pos);
bool res=hascycle(head);
cout<<"Output: "<<(res? "true (Cycle detected)" : "false (No cycle)")<<endl;
return 0;
}

Time Complexity: O(n)

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

OUTPUT:

CRITERION MAX MARKS


MARKS AWARDED
Preparation 30
Lab Performance 30
Viva voce and
completion of 40
record
Total 100
Faculty Signature

RESULT:

Thus, The algorithm to detect cycles in a graph was successfully executed and the output was
verified.

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

Ex.No: 05
Develop algorithms for topological sorting.
Date:

AIM:
To implement the algorithms for topological sorting.

QUESTION 1:

PSEUDOCODE:
int findJudge(int N, vector<vector<int>>& trust) {
vector<int> in(N + 1), out(N + 1);
for (auto a : trust) {
++out[a[0]];
++in[a[1]];
}
for (int i = 1; i <= N; ++i) {
if (in[i] == N - 1 && out[i] == 0) return i;
}
return -1;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
int findJudge(int N, vector<vector<int>>& trust) {
vector<int> in(N + 1), out(N + 1);
for (auto a : trust) {
++out[a[0]];
++in[a[1]];
}
for (int i = 1; i <= N; ++i) {
if (in[i] == N - 1 && out[i] == 0) return i;
}
return -1;
}
int main() {
int N, T;
cout << "Enter the number of people: ";
cin >> N;
cout << "Enter the number of trust relationships: ";
cin >> T;
vector<vector<int>> trust(T, vector<int>(2));
cout << "Enter the trust relationships:\n";
for (int i = 0; i < T; ++i) {
cout << "Trust " << i + 1 << ": ";
cin >> trust[i][0] >> trust[i][1];
}
int judge = findJudge(N, trust);

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

cout<<judge<<endl;
return 0;
}
Time Complexity: O(T+N)
OUTPUT:

QUESTION 2:

PSEUDOCODE:
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<int> vis(n, 0);
vector<vector<int>> adj(n);
for (auto it : edges) {
adj[it[0]].push_back(it[1]);
adj[it[1]].push_back(it[0]);
}
function<bool(int)> dfs = [&](int node) {
vis[node] = 1;
if (node == destination) return true;
for (auto it : adj[node]) {
if (!vis[it]) {
if (dfs(it)) return true;
}
}
return false;
};
return dfs(source);
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
vector<int> vis(n, 0);
vector<vector<int>> adj(n);
for (auto it : edges) {
adj[it[0]].push_back(it[1]);
adj[it[1]].push_back(it[0]);
}
function<bool(int)> dfs = [&](int node) {
vis[node] = 1;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

if (node == destination) return true;


for (auto it : adj[node]) {
if (!vis[it]) {
if (dfs(it)) return true;
}
}
return false;
};
return dfs(source);
}
int main() {
int n, m, source, destination;
cout << "Enter the number of vertices: ";
cin >> n;
cout << "Enter the number of edges: ";
cin >> m;
vector<vector<int>> edges(m, vector<int>(2));
cout << "Enter the edges:\n";
for (int i = 0; i < m; ++i) {
cout << "Edge " << i + 1 << ": ";
cin >> edges[i][0] >> edges[i][1];
}
cout << "Enter the source vertex: ";
cin >> source;
cout << "Enter the destination vertex: ";
cin >> destination;
cout <<(validPath(n, edges, source, destination) ? "True" : "False")<< endl;
return 0;
}
Time Complexity: O(N+E)

OUTPUT:

QUESTION 3:

PSEUDOCODE:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) {
return root;
}

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

TreeNode* left = lowestCommonAncestor(root->left, p, q);


TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) {
return root;
}
return left ? left : right;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root || root == p || root == q) {
return root;
}
TreeNode* left = lowestCommonAncestor(root->left, p, q);
TreeNode* right = lowestCommonAncestor(root->right, p, q);
if (left && right) {
return root;
}
return left ? left : right;
}
TreeNode* buildTree(const vector<int>& nodes, int index) {
if (index >= nodes.size() || nodes[index] == -1) {
return nullptr;
}
TreeNode* root = new TreeNode(nodes[index]);
root->left = buildTree(nodes, 2 * index + 1);
root->right = buildTree(nodes, 2 * index + 2);
return root;
}
TreeNode* findNode(TreeNode* root, int val) {
if (!root || root->val == val) {
return root;
}
TreeNode* left = findNode(root->left, val);
if (left) return left;
return findNode(root->right, val);
}
int main() {
int n,pv,qv;
vector<int> nodes;
cout<<"Enter no of nodes:";
cin>>n;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

cout<<"Enter "<<n<<" values:";


for(int i=0;i<n;i++){
int v;
cin>>v;
nodes.push_back(v);
}
cout<<"Enter valur of p:";
cin>>pv;
cout<<"Enter valur of q:";
cin>>qv;
TreeNode* root = buildTree(nodes, 0);
TreeNode* p = findNode(root, pv);
TreeNode* q = findNode(root, qv);
TreeNode* lca = lowestCommonAncestor(root, p, q);
cout << "LCA = " << (lca ? lca->val : -1) << endl;
return 0;
}
Time Complexity: O(n)

OUTPUT:

QUESTION 4:

PSEUDO CODE:
vector<int> countFrequency(const string& str) {
vector<int> frequency(26, 0);
for (char c : str) {
frequency[c - 'a']++;
}
return frequency;
}
vector<int> intersection(const vector<int>& a, const vector<int>& b) {
vector<int> t(26, 0);
for (int i = 0; i < 26; i++) {
t[i] = min(a[i], b[i]);
}
return t;
}
vector<string> commonChars(vector<string>& words) {

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

vector<int> last = countFrequency(words[0]);


for (int i = 1; i < words.size(); i++) {
last = intersection(last, countFrequency(words[i]));
}
vector<string> result;
for (int i = 0; i < 26; i++) {
while (last[i] > 0) {
result.push_back(string(1, 'a' + i));
last[i]--;
}
}
return result;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
vector<int> countFrequency(const string& str) {
vector<int> frequency(26, 0);
for (char c : str) {
frequency[c - 'a']++;
}
return frequency;
}
vector<int> intersection(const vector<int>& a, const vector<int>& b) {
vector<int> t(26, 0);
for (int i = 0; i < 26; i++) {
t[i] = min(a[i], b[i]);
}
return t;
}
vector<string> commonChars(vector<string>& words) {
vector<int> last = countFrequency(words[0]);
for (int i = 1; i < words.size(); i++) {
last = intersection(last, countFrequency(words[i]));
}
vector<string> result;
for (int i = 0; i < 26; i++) {
while (last[i] > 0) {
result.push_back(string(1, 'a' + i));
last[i]--;
}
}
return result;
}
int main() {
int n;
cout << "Enter number of words: ";
cin >> n;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

vector<string> words(n);
cout << "Enter the words: " << endl;
for (int i = 0; i < n; i++) {
cin >> words[i];
}
vector<string> result = commonChars(words);
cout << "Common characters: ";
for (const string& s : result) {
cout << s << " ";
}
cout << endl;
return 0;
}

Time Complexity: O(n)

OUTPUT:

CRITERION MAX MARKS


MARKS AWARDED
Preparation 30
Lab Performance 30
Viva voce and
completion of 40
record
Total 100
Faculty Signature

RESULT:

Thus, The algorithm to solve topological sorting was successfully executed and the output was
verified.

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

Ex.No: 06
Implement graph coloring algorithms.
Date:

AIM:
To implement the graph coloring algorithms.

QUESTION 1:
PSEUDOCODE:
bool canMakeSquare(vector<vector<char>>& grid) {
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
int w = 0, b = 0;
if(grid[i][j] == 'B') b++;
else w++;
if(grid[i][j+1] == 'B') b++;
else w++;
if(grid[i+1][j+1] == 'B') b++;
else w++;
if(grid[i+1][j] == 'B') b++;
else w++;
if(w >= 3 || b >= 3) return true;
}}
return false;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
bool canMakeSquare(vector<vector<char>>& grid) {
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
int w = 0, b = 0;
if(grid[i][j] == 'B') b++;
else w++;
if(grid[i][j+1] == 'B') b++;
else w++;
if(grid[i+1][j+1] == 'B') b++;
else w++;
if(grid[i+1][j] == 'B') b++;
else w++;
if(w >= 3 || b >= 3) return true;
}}
return false;
}
int main() {
vector<vector<char>> grid(3, vector<char>(3));

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

cout << "Enter the 3x3 grid (B for black and W for white):" << endl;
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
cin >> grid[i][j];
}}
if (canMakeSquare(grid)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
Time Complexity: O(1)
OUTPUT:

QUESTION 2:
PSEUDOCODE:
bool checkTwoChessboards(string coordinate1, string coordinate2) {
int one = (coordinate1[0] - 'a') + (coordinate1[1] - '0');
int two = (coordinate2[0] - 'a') + (coordinate2[1] - '0');
return one % 2 == two % 2;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
bool checkTwoChessboards(string coordinate1, string coordinate2) {
int one = (coordinate1[0] - 'a') + (coordinate1[1] - '0');
int two = (coordinate2[0] - 'a') + (coordinate2[1] - '0');
return one % 2 == two % 2;
}
int main() {
string coordinate1, coordinate2;
cout << "Enter the first coordinate: ";
cin >> coordinate1;
cout << "Enter the second coordinate: ";
cin >> coordinate2;
if (checkTwoChessboards(coordinate1, coordinate2)) {
cout << "true" << endl;
} else {

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

cout << "false" << endl;


}
return 0;
}
Time Complexity: O(1)
OUTPUT:

QUESTION 3:
PSEUDOCODE:
int minimumOperations(vector<vector<int>>& grid) {
int ans = 0;
for(int c = 0; c < grid[0].size(); ++c){
for(int r = 1; r < grid.size(); ++r){
if(grid[r][c] > grid[r-1][c]) continue;
ans += grid[r-1][c] + 1 - grid[r][c];
grid[r][c] = grid[r-1][c] + 1;
}}
return ans;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
int minimumOperations(vector<vector<int>>& grid) {
int ans = 0;
for(int c = 0; c < grid[0].size(); ++c){
for(int r = 1; r < grid.size(); ++r){
if(grid[r][c] > grid[r-1][c]) continue;
ans += grid[r-1][c] + 1 - grid[r][c];
grid[r][c] = grid[r-1][c] + 1;
}}
return ans;
}
int main() {
int m, n;
cout << "Enter number of rows : ";
cin >> m;
cout << "Enter number of columns : ";
cin >> n;
vector<vector<int>> grid(m, vector<int>(n));
cout << "Enter the grid values:" << endl;
for(int i = 0; i < m; i++) {

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

for(int j = 0; j < n; j++) {


cin >> grid[i][j];
}}
cout << "Minimum operations: " << minimumOperations(grid) << endl;
return 0;
}
Time Complexity: O(m * n)
OUTPUT:

QUESTION 4:
PSEUDOCODE:
bool checkValid(vector<vector<int>>& matrix) {
const int n = matrix.size();
bitset<101> col_hasX[101] = {0};
for(int i = 0; i < n; i++) {
bitset<101> row_hasX = 0;
for(int j = 0; j < n; j++) {
int x = matrix[i][j];
if(row_hasX[x]) return false;
else row_hasX[x] = 1;
if(col_hasX[j][x]) return false;
else col_hasX[j][x] = 1;
}}
return true;}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
bool checkValid(vector<vector<int>>& matrix) {
const int n = matrix.size();
bitset<101> col_hasX[101] = {0};
for(int i = 0; i < n; i++) {
bitset<101> row_hasX = 0;
for(int j = 0; j < n; j++) {
int x = matrix[i][j];
if(row_hasX[x]) return false;
else row_hasX[x] = 1;
if(col_hasX[j][x]) return false;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

else col_hasX[j][x] = 1;
}}
return true;
}
int main() {
int n;
cout << "Enter the size of the matrix: ";
cin >> n;
vector<vector<int>> matrix(n, vector<int>(n));
cout << "Enter the elements of the matrix:" << endl;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cin >> matrix[i][j];
}}
if(checkValid(matrix)) {
cout << "true" << endl;
} else {
cout << "false" << endl;
}
return 0;
}
Time Complexity: O(n^2)
OUTPUT:

CRITERION MAX MARKS


MARKS AWARDED
Preparation 30
Lab Performance 30
Viva voce and
completion of 40
record
Total 100
Faculty Signature

RESULT:

Thus, The algorithm to solve graph coloring algorithms was successfully executed and the output
was verified.

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

Ex.No: 07
Implement pattern matching algorithms.
Date:
AIM:
To Implement the pattern matching algorithms.

QUESTION 1:
PSEUDOCODE:
bool repeatedSubstringPattern(string s) {
int n = s.size();
for (int i = n / 2; i >= 1; i--) {
if (n % i == 0) {
if (s.substr(0, n - i) == s.substr(i)) return true;
}
}
return false;
}
SOURCE CODE:
#include <iostream>
using namespace std;
bool repeatedSubstringPattern(string s) {
int n = s.size();
for (int i = n / 2; i >= 1; i--) {
if (n % i == 0) {
if (s.substr(0, n - i) == s.substr(i)) return true;
}}
return false;
}
int main() {
string s;
cout << "Enter a string: ";
cin >> s;
if (repeatedSubstringPattern(s))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
Time Complexity: O(n^2)
OUTPUT:

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

QUESTION 2:
PSEUDOCODE:
bool hasMatch(string s, string p) {
int x = p.find("*");
string b = p.substr(0, x);
string e = p.substr(x + 1);
int i = s.find(b);
int j = s.find(e, i + b.size());
return (i != -1 && j != -1);
}
SOURCE CODE:
#include <iostream>
using namespace std;
bool hasMatch(string s, string p) {
int x = p.find("*");
string b = p.substr(0, x);
string e = p.substr(x + 1);
int i = s.find(b);
int j = s.find(e, i + b.size());
return (i != -1 && j != -1);
}
int main() {
string s, p;
cout << "Enter the string: ";
cin >> s;
cout << "Enter the pattern: ";
cin >> p;
if (hasMatch(s, p))
cout << "True" << endl;
else
cout << "False" << endl;
return 0;
}
Time Complexity: O(n)
OUTPUT:

QUESTION 3:
PSEUDOCODE:
int numSpecial(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size(), res = 0;

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

vector<int> rows(m), cols(n);


for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
rows[i] += mat[i][j];
cols[j] += mat[i][j];
}}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res += (rows[i] == 1 && cols[j] == 1 && mat[i][j]);
}
}
return res;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
int numSpecial(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size(), res = 0;
vector<int> rows(m), cols(n);
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
rows[i] += mat[i][j];
cols[j] += mat[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res += (rows[i] == 1 && cols[j] == 1 && mat[i][j]);
}}
return res;
}
int main() {
int m, n;
cout << "Enter number of rows: ";
cin >> m;
cout << "Enter number of columns: ";
cin >> n;
vector<vector<int>> mat(m, vector<int>(n));
cout << "Enter the binary matrix values:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> mat[i][j];
}
}
cout << "Number of special positions: " << numSpecial(mat) << endl;
return 0;
}
Time Complexity: O(m × n)

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

OUTPUT:

QUESTION 4:
PSEUDOCODE:
vector<int> luckyNumbers(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int maxCols[50] = {};
vector<int> res;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
maxCols[i] = max(maxCols[i], matrix[j][i]);
for (int i = 0; i < m; i++) {
int minRow = matrix[i][0], colIndex = 0;
for (int j = 1; j < n; j++) {
if (matrix[i][j] < minRow) {
minRow = matrix[i][j];
colIndex = j;
}}
if (minRow == maxCols[colIndex])
res.push_back(minRow);
}
return res;
}
SOURCE CODE:
#include <bits/stdc++.h>
using namespace std;
vector<int> luckyNumbers(vector<vector<int>>& matrix) {
int m = matrix.size(), n = matrix[0].size();
int maxCols[50] = {};
vector<int> res;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
maxCols[i] = max(maxCols[i], matrix[j][i]);
for (int i = 0; i < m; i++) {
int minRow = matrix[i][0], colIndex = 0;
for (int j = 1; j < n; j++) {
if (matrix[i][j] < minRow) {

717823F229
INFORMATION TECHNOLOGY 23CSR405 & ADVANCED ALGORITHMS LABORATORY

minRow = matrix[i][j];
colIndex = j;
}}
if (minRow == maxCols[colIndex])
res.push_back(minRow);
}
return res;
}
int main() {
int m, n;
cout << "Enter number of rows: ";
cin >> m;
cout << "Enter number of columns: ";
cin >> n;
vector<vector<int>> matrix(m, vector<int>(n));
cout << "Enter the matrix values:" << endl;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}}
vector<int> result = luckyNumbers(matrix);
cout << "Lucky Numbers: ";
for (int num : result)
cout << num << " ";
cout << endl;
return 0;
}
Time Complexity: O(m × n)
OUTPUT:

CRITERION MAX MARKS


MARKS AWARDED
Preparation 30
Lab Performance 30
Viva voce and
completion of 40
record
Total 100
Faculty Signature

RESULT:

Thus, The algorithm to solve pattern matching algorithms was successfully executed and the output
was verified.

717823F229

You might also like