解:
#include<iostream>
#include<vector>
void createMatrix(std::vector<std::vector<int>> & _grid);
int findRotOrange(std::vector<std::vector<int>> & _grid);
bool rotNeiborOrange(std::vector<std::vector<int>> & _grid,const int _r,const int _c);
int main()
{
std::vector<std::vector<int>>grid;
createMatrix(grid);
std::cout<<findRotOrange(grid)<<std::endl;
return 0;
}
void createMatrix(std::vector<std::vector<int>> & _grid) {
int row;//行
int col;//列
std::cout << "请输入矩阵的行: ";
std::cin >> row;
std::cin.get();
std::cout << "请输入矩阵的列: ";
std::cin >> col;
std::cin.get();
std::cout << "初始化矩阵元素:\n";
for (int i = 0; i < row; i++)
{
std::vector<int>tempArr;
for (int j = 0; j < col; j++)
{
int temp;
std::cout << "请输入第 " << i + 1 << " 行,第 " << j + 1 << " 个元素: ";
std::cin >> temp;
std::cin.get();
tempArr.push_back(temp);
}
_grid.push_back(tempArr);
}
}
int findRotOrange(std::vector<std::vector<int>> & _grid) {
int r = _grid.size();
int c = _grid[0].size();
int min_minutes = 0;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
if (_grid[i][j] == 2)
{
bool isTrue = rotNeiborOrange(_grid, i, j);
if(isTrue)
++min_minutes;
}
}
}
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
std::cout << _grid[i][j] << " ";
}
std::cout << std::endl;
}
int flag = 0;
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
if (_grid[i][j] == 1)
{
std::cout << "第 " << i + 1 << " 行,第 " << j + 1 << " 列永远不会腐烂\n";
++flag;
}
}
}
if (flag == 0)
return min_minutes;
else
return -1;
}
bool rotNeiborOrange(std::vector<std::vector<int>> & _grid, const int _r, const int _c) {
int flag = 0;
int r = _grid.size();
int c = _grid[0].size();
if (_r - 1 >= 0 && _grid[_r - 1][_c] == 1)
{
_grid[_r - 1][_c] = 2;
++flag;
}
if (_r + 1 < r && _grid[_r + 1][_c] == 1)
{
_grid[_r + 1][_c] = 2;
++flag;
}
if (_c - 1 >= 0 && _grid[_r][_c - 1] == 1)
{
_grid[_r][_c - 1] = 2;
++flag;
}
if (_c + 1 < c && _grid[_r][_c + 1] == 1)
{
_grid[_r][_c + 1] = 2;
++flag;
}
if (flag == 0)
return false;
else
return true;
}