위험한 지역 몇개인지 알려주기

Yun Young Choi·2022년 10월 19일

CodingTest-C

목록 보기
12/15
post-thumbnail

처음에 긴가민가 하면서 이해가 잘 안됐지만 두 번쯤 읽었을 때 아하!했다.


main 설명

int main() {
    int height[4][4] = {{3, 6, 2, 8}, {7, 3, 4, 2}, {8, 6, 7, 3}, {5, 3, 2, 9}};
    int height_len = 4;
    int ret = solution(height, height_len = 4);

    printf("solution 함수의 반환 값은 %d 입니다.\n", ret);
}
  1. height 배열에 4행/4열 구조로 선언
  2. height 배열의 길이는 4
  3. ret 변수에 solution 함수 반환값을 저장

solution 설명

int solution(int height[][4], int height_len) {
    int count = 0;
		int test[6][6];

		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				test[i][j] = 51;
			}
		}

		for (int i = 1; i < 5; i++) {
			for (int j = 1; j < 5; j++) {
				test[i][j] = height[i-1][j-1];
			}
		}

		for (int i = 1; i <= height_len; i++) {
			for (int j = 1; j <= height_len; j++) {
				if (test[i][j] < test[i][j - 1] && test[i][j] < test[i + 1][j] && test[i][j] < test[i][j + 1] && test[i][j] < test[i - 1][j]) {
					count++;
				}
			}
		}
    return count;
}

  1. 위험 지역 개수를 셀 count 변수를 0으로 초기화
  2. test 6행6열 배열을 선언한다.

    한 값과 상하좌우 값을 비교했을 때 한 값 < 상하좌우값 이면 count++
    (그런데 벽에 있는 값들은 상하좌우 값을 비교했을 때 값이 없음)

    6행 6열 배열안에 4행 4열이 들어갈 수 있도록 한다.

  3. test의 값을 모두 51로 초기화한다. (각 지역의 높이는 1이상 50이하인 자연수)
  4. 그리고 test 2행 2열부터 height 배열의 값을 차례대로 삽입한다.
  5. 그리고 이중 for문을 돌려 상하좌우를 비교하고 한 값 < 상하좌우값 이면 count++한다

빈칸 채우기

int solution(int height[][4], int height_len) {
    int count = 0;
		int test[6][6];

		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				test[i][j] = 51;
			}
		}

		for (int i = 1; i < 5; i++) {
			for (int j = 1; j < 5; j++) {
				test[i][j] = height[i-1][j-1];
			}
		}

		for (int i = 1; i <= height_len; i++) {
			for (int j = 1; j <= height_len; j++) {
				if (test[i][j] < test[i][j - 1] && test[i][j] < test[i + 1][j] && test[i][j] < test[i][j + 1] && test[i][j] < test[i - 1][j]) {
					count++;
				}
			}
		}
    return count;
}

전체 코드

int solution(int height[][4], int height_len) {
    int count = 0;
		int test[6][6];

		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				test[i][j] = 51;
			}
		}

		for (int i = 1; i < 5; i++) {
			for (int j = 1; j < 5; j++) {
				test[i][j] = height[i-1][j-1];
			}
		}

		for (int i = 1; i <= height_len; i++) {
			for (int j = 1; j <= height_len; j++) {
				if (test[i][j] < test[i][j - 1] && test[i][j] < test[i + 1][j] && test[i][j] < test[i][j + 1] && test[i][j] < test[i - 1][j]) {
					count++;
				}
			}
		}
    return count;
}

int main() {
    int height[4][4] = {{3, 6, 2, 8}, {7, 3, 4, 2}, {8, 6, 7, 3}, {5, 3, 2, 9}};
    int height_len = 4;
    int ret = solution(height, height_len = 4);

    printf("solution 함수의 반환 값은 %d 입니다.\n", ret);
}

실행 결과


profile
안냥하세요

0개의 댓글