#include <iostream>
#include <windows.h>
#include <string>
#include <fstream>
#define N 10
using namespace std;
bool isPeak(int a[N][N], int i, int j);
bool isValley(int b[N][N], int i, int j);
void extremes(int c[N][N],int i,int j);
int main() {
int map[N][N] = { 0 };
int row = 0;
int col = 0;
int count = 0;
int count1 = 0;
string filename;
ifstream file;
while (1)
{
system("cls");
cout << "请输入文件名:";
cin >> filename;
file.open(filename.c_str());
if (!(file.fail())) {
break;
}
else
{
cout << "文件输入错误,请重新输入!" << endl;
system("pause");
}
}
file >> row >> col;
if (row > N || col > N) {
cout << "网格太大,请调整网格!" << endl;
exit(1);
}
//从数据文件读数据到数组
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
file >> map[i][j];
}
}
//判断并打印峰值位置
for (int i = 1; i < row - 1; i++) {
for (int j = 1; j < col - 1; j++) {
if (isPeak(map, i, j)) {
printf("峰值为:%d,出现在(%d,%d)\n", map[i][j],i,j);
count++;
}
}
}
cout << "一共有" << count << "个峰点" << endl;
//判断并打印谷点位置
for (int i = 1; i < row - 1; i++) {
for (int j = 1; j < col - 1; j++) {
if (isValley(map, i, j)) {
printf("谷点为:%d,出现在(%d,%d)\n", map[i][j], i, j);
count1++;
}
}
}
cout << "一共有" << count1 << "个谷点" << endl;
extremes(map,row,col);
//关闭文件
file.close();
//结束程序
system("pause");
return 0;
}
bool isPeak(int a[N][N], int i, int j) {
if (a[i - 1][j] < a[i][j] &&
a[i + 1][j] < a[i][j] &&
a[i][j - 1] < a[i][j] &&
a[i][j + 1] < a[i][j] &&
a[i - 1][j - 1] < a[i][j] &&
a[i - 1][j + 1] < a[i][j] &&
a[i + 1][j + 1] < a[i][j] &&
a[i + 1][j - 1] < a[i][j]) {
return true;
}
else {
return false;
}
}
bool isValley(int b[N][N], int i, int j) {
if (b[i - 1][j] > b[i][j] &&
b[i + 1][j] > b[i][j] &&
b[i][j - 1] > b[i][j] &&
b[i][j + 1] > b[i][j]) {
return true;
}
else {
return false;
}
}
void extremes(int c[N][N], int x, int y) {
int max = c[0][0];
int min = c[0][0];
int pos[2][2]; //pos[0][0] pos[0][1] 保存最高点的坐标 pos[1][0] pos[1][1] 保存最低点的坐标
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
if (max < c[i][j]) {
max = c[i][j];
pos[0][0] = i;
pos[0][1] = j;
}
else if (min > c[i][j]) {
min = c[i][j];
pos[1][0] = i;
pos[1][1] = j;
}
}
}
printf("海拔最大值为:%d,出现在(%d,%d)\n", max, pos[0][0], pos[0][1]);
printf("海拔最小值为:%d,出现在(%d,%d)\n", min, pos[1][0], pos[1][1]);
}