使用 C++ 查找二进制矩阵中的重复行
假设我们有一个二进制矩阵。接下来我们将介绍如何在这类矩阵中查找重复行。假设该矩阵如下所示 −
1 | 1 | 0 | 1 | 0 | 1 |
0 | 0 | 1 | 0 | 0 | 1 |
1 | 0 | 1 | 1 | 0 | 0 |
1 | 1 | 0 | 1 | 0 | 1 |
0 | 0 | 1 | 0 | 0 | 1 |
0 | 0 | 1 | 0 | 0 | 1 |
在第 3、4、5 个位置有重复行。
为了解决这个问题,我们将使用 Trie 树。Trie 树是一种高效数据结构,用于高效存取字符集较小的数据。搜索复杂度随着键值长度而优化。因此,我们首先将插入的二进制 trie。如果新添加的行已存在,则该行为重复行。
示例
#include<iostream> using namespace std; const int MAX = 100; class Trie { public: bool leaf_node; Trie* children[2]; }; Trie* getNode() { Trie* node = new Trie; node->children[0] = node->children[1] = NULL; node->leaf_node = false; return node; } bool insert(Trie*& head, bool* arr, int N) { Trie* curr = head; for (int i = 0; i < N; i++) { if (curr->children[arr[i]] == NULL) curr->children[arr[i]] = getNode(); curr = curr->children[arr[i]]; } if (curr->leaf_node) return false; return (curr->leaf_node = true); } void displayDuplicateRows(bool matrix[][MAX], int M, int N) { Trie* head = getNode(); for (int i = 0; i < M; i++) if (!insert(head, matrix[i], N)) cout << "There is a duplicate row at position: "<< i << endl; } int main() { bool mat[][MAX] = { {1, 1, 0, 1, 0, 1}, {0, 0, 1, 0, 0, 1}, {1, 0, 1, 1, 0, 0}, {1, 1, 0, 1, 0, 1}, {0, 0, 1, 0, 0, 1}, {0, 0, 1, 0, 0, 1}, }; displayDuplicateRows(mat, 6, 6); }
输出
There is a duplicate row at position: 3 There is a duplicate row at position: 4 There is a duplicate row at position: 5
广告