数组练习--人工智能之地形导航系统

项目要求:从文件中读取数据,判断并输出峰点

//-------------------------  map.txt  ---------------------
6  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

//-------------------------  main.cpp  ---------------------
#include <iostream>
#include <fstream>  // 文件流库函数
#include <string>

#define MAPMAX 64
using namespace std;

bool isPeak(int map[][MAPMAX], int i, int j);

int main()
{
    int rows = 0;   // 从文件读取的行
    int cols = 0;   // 从文件读取的列
    int map[MAPMAX][MAPMAX] = { 0 };
    string fileName;
    ifstream file;
    cout << "请输入要打开的文件名";
    cin >> fileName;

    // 打开文件
    file.open(fileName.c_str(), ios::in);
    if (file.fail())
    {
        cerr << "文件打开失败" << endl;
        exit(1);
    }

    file >> rows >> cols;
    if (rows > MAPMAX || cols > MAPMAX)
    {
        cerr << "网格太大,调整程序" << endl;
        exit(1);
    }

    // 从文件读取数据到数组
    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < cols; j++)
        {
            file >> map[i][j];
        }
    }

    // 判断并打印峰值的位置
    for (int i = 1; i < rows - 1; i++)
    {
        for (int j = 1; j < cols - 1; j++)
        {
            if (isPeak(map, i, j))
            {
                cout << "峰值出现在" << i << "行," << j << "列, 值为:" << map[i][j] << endl;
            }
        }
    }

    // 关闭文件
    file.close();
    return 0;
}

// 判断是否是峰值
bool isPeak(int map[][MAPMAX], int i, int j)
{
    if (map[i][j] > map[i - 1][j] &&
        map[i][j] > map[i + 1][j] &&
        map[i][j] > map[i][j + 1] &&
        map[i][j] > map[i][j - 1]
        )
    {
        return true;
    }
    else
    {
        return false;
    }
}

image

posted @ 2022-04-15 04:50  荒年、  阅读(35)  评论(0编辑  收藏  举报