gpt4 book ai didi

c++ - 矩阵C++每一行中的最小元素

转载 作者:行者123 更新时间:2023-12-03 07:00:39 29 4
gpt4 key购买 nike

这段代码只能返回矩阵中的一个最小元素,但是如果我想返回每一行中的最小元素怎么办?我需要在 C++ 中使用递归函数。谢谢你的帮助

#include<iostream>
using namespace std;
int smallest(int** arr, int rows, int columns, int column_index = 0)
{
if (rows <= 0 || column_index >= columns)
return INT_MAX;


if (rows == 1)
return min(*(*arr + column_index),
smallest(arr, 1, columns - 1,
column_index + 1));


return min(smallest(arr, 1, columns),
smallest(arr + 1, rows - 1, columns));
}
int main()
{
int row, col, index=0;
cin >> row;
cin >> col;
int** arr;
arr = new int* [row];
for (int i = 0; i < row; i++) {
arr[i] = new int[col];
for (int j = 0; j < col; j++) {
cin >> arr[i][j];
}
}
cout<<smallest(arr, row, col, index);
return 0;
}

最佳答案

如果您使用标准算法,我认为这么多代码就足够了 - std::min_element :

#include <algorithm>
#include <iostream>
#include <vector>

int main() {
int r, c;
std::cin >> r >> c;
std::vector<std::vector<int>> mat(r, std::vector<int>(c));
for (auto &&row : mat)
for (auto &&ele : row)
std::cin >> ele;
for (auto &&row : mat)
std::cout << *std::min_element(row.begin(), row.end()) << std::endl;
}

如果你想按照自己的方式做(老派风格,使用递归),那么做这样的事情。您只需要在调用 smallest 时修复行的索引.下面是一些不言自明的代码:
#include <algorithm>
#include <iostream>

// here row_index represents the index of row and col represents the number of
// elements in that row which are not yet traversed (counted from beginning)
int smallest(int **arr, int row_index, int col) {

// only first element is not traversed
if (col == 1)
return arr[row_index][0];

// return minimum of last element and value returned by recursive call for
// first col - 1 elements
return std::min(arr[row_index][col - 1], smallest(arr, row_index, col - 1));
}

int main() {
int row, col;
std::cin >> row;
std::cin >> col;
int **arr = new int *[row];
for (int i = 0; i < row; i++) {
arr[i] = new int[col];
for (int j = 0; j < col; j++)
std::cin >> arr[i][j];
}

// call the function for each row
for (int i = 0; i < row; i++)
std::cout << "Smallest element in row " << i + 1 << " : "
<< smallest(arr, i, col) << '\n';
}

关于c++ - 矩阵C++每一行中的最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64087793/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com