假设下面的数据代表一个 6 x 7 的网格, 加了下划线的网格即为峰点。
5039 5127 5238 5259 5248 5310 5299
5150 5392 5410 5401 5320 5820 5321
5290 5560 5490 5421 5530 5831 5210
5110 5429 5430 5411 5459 5630 5319
4920 5129 4921 5821 4722 4921 5129
5023 5129 4822 4872 4794 4862 4245
为了描述峰点的位置,我们需要使用一个位置方案:使用二维数组描述
假定左上角是[0][0],那么向下移动,则行号加 1;向右移动,则列号加 1,
那么这些峰点的位置就可以描述为:[2][1] [2][5] [4][3]。
位置确定后,与周围 4 个邻节点比较即可确定峰点!(注:网格边界点缺乏 4
个相邻点不计算峰点)
地形数据保存于文件中。
算法设计
1) 将地形数据从文件读入二维数组;
2) 逐行遍历二维数组的每个元素,确定是否峰值并打印结果。
#include <iostream>
#include <fstream>
#include <string>
#include <Windows.h>
using namespace std;
bool isPeak(const double grid[64][64], int r, int c);
int main(){
int nrows, ncols;
double map[64][64];
string filename;
ifstream file;
cout <<"请输入文件名.\n";
cin >> filename;
file.open(filename.c_str());
if(file.fail()){
cerr<<"打开输入文件出错.\n";
exit(1);
}
file>>nrows>>ncols;
if(nrows > 64 || ncols > 64){
cerr<<"网格太大,调整程序.\n";
exit(1);
}
//从数据文件读数据到数组
for(int i=0; i<nrows; ++i){
for(int j=0; j<ncols; ++j){
file>>map[i][j];
}
}
//判断并打印峰值位置
for(int i=1;i<nrows-1; ++i){
for(int j=1;j<ncols-1; ++j){
if(isPeak(map, i, j)){
cout<<"峰值出现在行: "<<i<<" 列: "<<j<<endl;
}
}
}
system("pause");
//关闭文件
file.close();
//结束程序
return 0;
}
bool isPeak(const double grid[64][64], int i, int j){
if((grid[i-1][j]<grid[i][j]) &&
(grid[i+1][j]<grid[i][j]) &&
(grid[i][j-1]<grid[i][j]) &&
(grid[i][j+1]<grid[i][j])) {
return true;
}else{
return false;
}
}