Notice
Recent Posts
Recent Comments
Link
«   2026/07   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

hwooo

BOJ (Java) 14890번: 경사로 본문

Study/Algorithm

BOJ (Java) 14890번: 경사로

hwooo 2025. 8. 14. 14:32

https://www.acmicpc.net/problem/14890


풀이

같은 높이인 칸의 연속된 개수를 세어서 사용한다.

올라가는 경우에는 현재까지 세어 둔 수를 활용하고, 내려가는 경우에는 낮은 칸의 갯수를 센다.

각 칸의 개수가 L개보다 작다면 false를 반환한다.

 

이 때 내려갔다가 올라가는 경우에는 경사로가 겹치면 안 되기에 L의 2배 길이가 필요하다.

L = 2일 때, 3 3 2 2 3 3 (X), 3 3 2 2 2 2 3 3 (O)

따라서 내려가는 경우에는 세어둔 칸의 개수에서 L만큼을 빼서 다음 계산에 사용한다.


Java 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class Main {
	static int N, L;
	static int[][] map;
	public static void main(String[] args) throws IOException {
		// ---------여기에 코드를 작성하세요.---------------//
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		
		String[] inputs = bf.readLine().split(" ");
		N = Integer.parseInt(inputs[0]);
		L = Integer.parseInt(inputs[1]);
		
		map = new int[N][N];
		for (int i = 0; i < N; i++) {
			inputs = bf.readLine().split(" ");
			for (int j = 0; j < N; j++) {
				map[i][j] = Integer.parseInt(inputs[j]);
			}
		}
		
		int cnt = 0;
		for (int i = 0; i < N; i++) {
			cnt += checkRow(i);
			cnt += checkCol(i);
		}
		System.out.println(cnt);
	}
	private static int checkRow(int r) {
		int nowVal = map[r][0];
		int nowCnt = 1;
		for (int i = 1; i < N; i++) {
			if (map[r][i] == nowVal) {
				nowCnt++;
			}
			
			// 내려감
			else if (map[r][i] < nowVal) {
				if (nowVal - map[r][i] > 1) return 0; // 단차가 1 이상
				nowVal = map[r][i];
				nowCnt = 1;
				while (++i < N && map[r][i] == nowVal) { nowCnt++; } // 낮은 곳의 갯수 확인
				i--;
				if (nowCnt < L) return 0; // 갯수가 L보다 작을 때
				
				// L만큼 빼야 해당 칸에서 다음 칸으로 올라갈 때 계산 가능
				nowCnt -= L; 
			}
			
			// 올라감
			else {
				if (map[r][i] - nowVal > 1 || nowCnt < L) return 0;
				nowVal = map[r][i];
				nowCnt = 1;
			}
		}
		return 1;
	}
	private static int checkCol(int c) {
		int nowVal = map[0][c];
		int nowCnt = 1;
		for (int i = 1; i < N; i++) {
			if (map[i][c] == nowVal) {
				nowCnt++;
			}
			else if (map[i][c] < nowVal) {
				if (nowVal - map[i][c] > 1) return 0;
				nowVal = map[i][c];
				nowCnt = 1;
				while (++i < N && map[i][c] == nowVal) {nowCnt++; }
				i--;
				if (nowCnt < L) return 0;
				
				nowCnt -= L;
			}
			else {
				if (map[i][c] - nowVal > 1 || nowCnt < L) return 0;
				nowVal = map[i][c];
				nowCnt = 1;
			}
		}
		return 1;
	}

}