สมมติว่าเราเป็นเมทริกซ์ไบนารี ที่นี่เราจะมาดูวิธีค้นหาแถวที่ซ้ำกันในเมทริกซ์นั้น สมมติว่าเมทริกซ์เป็นเหมือน −
| 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 เป็นโครงสร้างข้อมูลที่มีประสิทธิภาพซึ่งใช้สำหรับที่แข็งแกร่งและดึงข้อมูลที่ชุดอักขระมีขนาดเล็ก ความซับซ้อนในการค้นหานั้นเหมาะสมที่สุดเมื่อพิจารณาจากความยาวของคีย์ ดังนั้นในตอนแรก เราจะแทรกไบนารีทดลอง หากแถวที่เพิ่มใหม่มีอยู่แล้วแสดงว่าซ้ำกัน
ตัวอย่าง
#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