ในปัญหานี้ เราได้รับอาร์เรย์สองมิติ mat[n][m] งานของเราคือการหาจำนวนขององค์ประกอบตำแหน่ง
องค์ประกอบจะเรียกว่าองค์ประกอบตำแหน่งหากองค์ประกอบเป็นองค์ประกอบสูงสุดหรือต่ำสุดของแถวหรือคอลัมน์
มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน
อินพุต
mat[][] = {2, 5, 7}
{1, 3, 4}
{5, 1, 3} ผลลัพธ์
8
คำอธิบาย
องค์ประกอบ 2, 5, 7, 1, 4, 5, 1, 3 เป็นองค์ประกอบตำแหน่ง
แนวทางการแก้ปัญหา
วิธีแก้ปัญหาอย่างง่ายคือการจัดเก็บองค์ประกอบสูงสุดและต่ำสุดของแต่ละแถวและคอลัมน์ แล้วตรวจสภาพและนับจำนวน
โปรแกรมเพื่อแสดงการทำงานของโซลูชันของเรา
ตัวอย่าง
#include <iostream>
using namespace std;
const int MAX = 100;
int countAllPositionalElements(int mat[][MAX], int m, int n){
int rowmax[m], rowmin[m];
int colmax[n], colmin[n];
for (int i = 0; i < m; i++) {
int rminn = 10000;
int rmaxx = -10000;
for (int j = 0; j < n; j++) {
if (mat[i][j] > rmaxx)
rmaxx = mat[i][j];
if (mat[i][j] < rminn)
rminn = mat[i][j];
}
rowmax[i] = rmaxx;
rowmin[i] = rminn;
}
for (int j = 0; j < n; j++) {
int cminn = 10000;
int cmaxx = -10000;
for (int i = 0; i < m; i++) {
if (mat[i][j] > cmaxx)
cmaxx = mat[i][j];
if (mat[i][j] < cminn)
cminn = mat[i][j];
}
colmax[j] = cmaxx;
colmin[j] = cminn;
}
int positionalCount = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if ((mat[i][j] == rowmax[i]) || (mat[i][j] ==
rowmin[i]) || (mat[i][j] == colmax[j]) || (mat[i][j] == colmin[j])){
positionalCount++;
}
}
}
return positionalCount;
}
int main(){
int mat[][MAX] = {
{ 2, 5, 7 },
{ 1, 3, 4 },
{ 5, 1, 3 }
};
int m = 3, n = 3;
cout<<"Number of positional elements is "<<countAllPositionalElements(mat, m, n);
return 0;
} ผลลัพธ์
Number of positional elements is 8