컨셉
주어진 m x m 행렬과 관련하여 문제는 행렬의 모든 행에 공통적인 모든 개별 요소를 결정하는 것입니다. 따라서 요소는 임의의 순서로 표시될 수 있습니다.
입력
mat[][] = { {13, 2, 15, 4, 17},
{15, 3, 2, 4, 36},
{15, 2, 15, 4, 12},
{15, 26, 4, 3, 2},
{2, 19, 4, 22, 15}
} 출력
2 4 15
방법
첫 번째 방법:세 개의 중첩 루프를 구현합니다. 첫 번째 행의 요소가 모든 후속 행에 존재하는지 확인하십시오. 여기서 시간 복잡도는 O(m^3)입니다. 중복 요소를 제어하려면 추가 공간이 필요할 수 있습니다.
두 번째 방법:행렬의 모든 행을 개별적으로 오름차순으로 정렬하거나 정렬합니다. 그래서 우리는 3개의 정렬된 배열에서 공통 요소를 결정하는 문제의 수정된 접근 방식을 구현합니다. 동일한 구현이 제공됩니다.
예시
// C++ implementation to find distinct elements
// common to all rows of a matrix
#include <bits/stdc++.h>
using namespace std;
const int MAX1 = 100;
// Shows function to individually sort
// each row in increasing order
void sortRows1(int mat1[][MAX1], int m){
for (int i=0; i<m; i++)
sort(mat1[i], mat1[i] + m);
}
// Shows function to find all the common elements
void findAndPrintCommonElements1(int mat1[][MAX1], int m){
//Used to sort rows individually
sortRows1(mat1, m);
// Shows current column index of each row is stored
// from where the element is being searched in
// that row
int curr_index1[m];
memset(curr_index1, 0, sizeof(curr_index1));
int f = 0;
for (; curr_index1[0]<m; curr_index1[0]++){
//Indicates value present at the current column index
// of 1st row
int value1 = mat1[0][curr_index1[0]];
bool present1 = true;
//Indicates 'value' is being searched in all the
// subsequent rows
for (int i=1; i<m; i++){
// Used to iterate through all the elements of
// the row from its current column index
// till an element greater than the 'value'
// is found or the end of the row is
// encountered
while (curr_index1[i] < m &&
mat1[i][curr_index1[i]] <= value1)
curr_index1[i]++;
// Now if the element was not present at the column
// before to the 'curr_index' of the row
if (mat1[i][curr_index1[i]-1] != value1)
present1 = false;
// Now if all elements of the row have
// been traversed
if (curr_index1[i] == m){
f = 1;
break;
}
}
// Now if the 'value' is common to all the rows
if (present1)
cout << value1 << " ";
// Now if any row have been completely traversed
// then no more common elements can be found
if (f == 1)
break;
}
}
// Driver program to test above
int main(){
int mat1[][MAX1] = { {13, 2, 15, 4, 17},{15, 3, 2, 4, 36},{15, 2, 15, 4, 12},
{15, 26, 4, 3, 2},{2, 19, 4, 22, 15}};
int m = 5;
findAndPrintCommonElements1(mat1, m);
return 0;
} 출력
2 4 15