เราได้รับเมทริกซ์ที่ประกอบด้วยจำนวนเต็ม เป้าหมายคือหาจำนวนแถวที่มีองค์ประกอบเหมือนกันทุกตัวในแถวนั้น
ตัวอย่าง
อินพุต:
matrix = [ [1, 1, 1, 1],
[2, 3, 2, 7],
[3, 3, 3, 3] ]
เอาต์พุต: 2
คำอธิบาย: แถว 0 มีแต่ 1, แถว 2 มีแต่ 3
อินพุต:
matrix = [ [1, 2, 3, 4],
[1, 2, 3, 4],
[1, 2, 3, 4] ]
เอาต์พุต: 0
คำอธิบาย: ทุกแถวมีองค์ประกอบต่างกัน
แนวทางการแก้ปัญหา
ใช้ set<int> สำหรับแต่ละแถว ใส่สมาชิกทุกตัวเข้าไป ถ้าขนาดของ set เท่ากับ 1 แสดงว่าแถวนั้นมีองค์ประกอบเหมือนกันทั้งหมด
การนำไปใช้ (Implementation)
#include <bits/stdc++.h>
using namespace std;
int same_rows(vector<vector<int>> matrix, int size) {
int count = 0;
for (int i = 0; i < size; i++) {
set<int> set_row;
for (int j = 0; j < matrix[i].size(); j++) {
set_row.insert(matrix[i][j]);
}
if (set_row.size() == 1) {
count++;
}
}
return count;
}
int main() {
vector<vector<int>> matrix = {
{2, 2, 2, 2},
{5, 5, 5, 5},
{2, 2, 2, 2},
{5, 5, 5, 5}
};
int size = matrix.size();
cout << "Count of rows in a matrix that consist of same element are: " << same_rows(matrix, size);
return 0;
}
เอาต์พุต
Count of rows in a matrix that consist of same element are: 4