안녕 세상아,

[c++/코드트리] 1이 3개 이상 있는 위치 본문

코드트리

[c++/코드트리] 1이 3개 이상 있는 위치

돈 많은 백수가 되고싶다 2024. 11. 23. 17:25

https://www.codetree.ai/missions/5/problems/place-more-than-3-ones/explanation

 

코드트리 | 코딩테스트 준비를 위한 알고리즘 정석

국가대표가 만든 코딩 공부의 가이드북 코딩 왕초보부터 꿈의 직장 코테 합격까지, 국가대표가 엄선한 커리큘럼으로 준비해보세요.

www.codetree.ai

dx, dy 사용해서 푸는 문제 연습중

 

#include <iostream>
using namespace std;

int main() {
    int dx[4] = { 0,1,0,-1 };
    int dy[4] = { 1,0,-1,0 };

    int n;
    cin >> n;

    int arr[101][101];
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cin >> arr[i][j];
        }
    }
    int ans = 0;  //정답
    int cnt = 0;  //3개 이상 카운트

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            cnt = 0;
            for (int k = 0; k < 4; k++) {
                int nx = i;
                int ny = j;
                if (nx + dx[k] < n && ny + dy[k] < n && nx + dx[k] >= 0 && ny + dy[k] >= 0) {
                    nx += dx[k];
                    ny += dy[k];
                    if (arr[nx][ny] == 1) {
                        cnt++;
                    }
                }
            }
            if (cnt >= 3) {
                ans++;
            }
        }
    }
    cout << ans;
    return 0;
}