
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find Orientation of a Pattern in a Matrix in C++
In this problem, we are given a matrix consisting of character values that make a pattern, we are also given a pattern to be found. Our task is to find the orientation (horizontal or vertical) of a pattern in a matrix.
Let’s take an example to understand the problem,
Input
mat[][] = { { r, a, m }, {a, m, c}, {w, f, t} } Patern : raw
Output
vertical
Solution Approach
A simple solution to the problem is by searching the M sized pattern in all the N rows of the matrix. This solution is ok but a more effective solution to the problem is by using the KML pattern matching algorithm for all rows and columns of the matrix.
Program to illustrate the working of our solution,
Example
#include<bits/stdc++.h> using namespace std; #define N 3 void calcLpsValues(char *pat, int M, int *lps) { int len = 0; int i = 1; lps[0] = 0; while (i < M) { if (pat[i] == pat[len]) { len++; lps[i++] = len; } else { if (len != 0) len = lps[len - 1]; else lps[i++] = 0; } } } int searchPattern(char *pat, char *txt) { int M = strlen(pat); int *lps = (int *)malloc(sizeof(int)*M); int j = 0; calcLpsValues(pat, M, lps); int i = 0; while (i < N) { if (pat[j] == txt[i]) { j++; i++; } if (j == M) return 1; else if (i < N && pat[j] != txt[i]) { if (j != 0) j = lps[j - 1]; else i = i + 1; } } return 0; } void findPatternOrientation(char mat[][N], char *pat) { char *col = (char*) malloc(N); for (int i = 0; i < N; i++) { if (searchPattern(pat, mat[i])) { cout<<"horizontal"; return; } for (int j = 0; j < N; j++) col[j] = *(mat[j] + i); if (searchPattern(pat, col)) cout<<"vertical"; } } int main() { char mat[N][N] = {{'r', 'a', 'm'}, {'a', 'm', 'c'}, {'w', 'f', 't'}}; char pattern[] = "raw"; cout<<"The orientation of the pattern in matrix is "; findPatternOrientation(mat, pattern); return 0; }
Output
The orientation of the pattern in matrix is vertical
Advertisements