본문 바로가기
알고리즘/C++

47. 봉우리 (2차원 배열 탐색)

by vivi 2021. 4. 5.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int main()
{
    //   freopen("input.txt", "rt", stdin);

    int n, i, j, cnt = 0;

    scanf("%d", &n);

    vector<vector<int>> a(n + 2, vector<int>(n + 2, 0));

    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; j++)
            scanf("%d", &a[i][j]);

    for (i = 1; i <= n; i++)
        for (j = 1; j <= n; 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])
                cnt++;
        }

    printf("%d", cnt);

    return 0;
}

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int a[51][51];
int dx[4] = {-1, 0, 1, 0};
int dy[4] = {0, 1, 0, -1};

int main()
{
    //   freopen("input.txt", "rt", stdin);

    int n, i, j, k, cnt = 0, flag;
	scanf("%d", &n);

    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= n; j++)
            scanf("%d", &a[i][j]);
    }

    for (i = 1; i <= n; i++)
    {
        for (j = 1; j <= n; j++)
        {

            flag = 0;
            for (k = 0; k < 4; k++)
            {

                if (a[i][j] <= a[i + dx[k]][j + dy[k]])
                {
                    flag = 1;
                    break;
                }
            }
            if (flag == 0)
                cnt++;
        }
    }

    printf("%d", cnt);

    return 0;
}

2차원 좌표에서 방향 벡터 배열을 만들어서 사용하는 방법도 있다.

댓글