본문 바로가기
알고리즘/구현

[백준 14890] 경사로 / 자바 / 구현

by 순원이 2024. 8. 6.

#문제         

레벨: G3
알고리즘: 구현

풀이시간: 1시간
힌트 참조 유무:

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

 


#문제 풀이        

문제를 보면 알겠지만 우리가 해야할 일은 명확하다. 모든 행을 검사하고 모든 열을 검사하면 된다. 그러나 조건이 많이 붙어있어 구현하는데 까다로울 수 있다. 해야 할 일이 명확하고 구현이 까다로운 경우는 밀고나가야한다. 이것은 구현문제이기 때문이다. dfs 혹은 bfs 혹은 dp 문제 같은 경우 해야 할 일이 명확하지는 않은데 구현이 지엽적인 것 같다고 느낄 때는 아이디어를 돌아볼 필요성이 있다.


#풀이 코드      

import java.util.*;
import java.io.*;

public class Main {
    static int N, L;
    static int[][] map;

    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        L = Integer.parseInt(st.nextToken());
        map = new int[N][N];

        for (int i = 0; i < N; i++) {
            st = new StringTokenizer(br.readLine());
            for (int j = 0; j < N; j++) {
                map[i][j] = Integer.parseInt(st.nextToken());
            }
        }

        int count = 0;
        for (int i = 0; i < N; i++) {
            if (checkRow(i)) count++;
            if (checkCol(i)) count++;
        }

        System.out.println(count);
    }

    static boolean checkRow(int row) {
        boolean[] slope = new boolean[N];
        for (int i = 0; i < N - 1; i++) {
            if (map[row][i] == map[row][i + 1]) continue;
            if (Math.abs(map[row][i] - map[row][i + 1]) > 1) return false;

            if (map[row][i] < map[row][i + 1]) {
                for (int j = 0; j < L; j++) {
                    if (i - j < 0 || slope[i - j] || map[row][i] != map[row][i - j]) return false;
                    slope[i - j] = true;
                }
            } else {
                for (int j = 1; j <= L; j++) {
                    if (i + j >= N || slope[i + j] || map[row][i + 1] != map[row][i + j]) return false;
                    slope[i + j] = true;
                }
            }
        }
        return true;
    }

    static boolean checkCol(int col) {
        boolean[] slope = new boolean[N];
        for (int i = 0; i < N - 1; i++) {
            if (map[i][col] == map[i + 1][col]) continue;
            if (Math.abs(map[i][col] - map[i + 1][col]) > 1) return false;

            if (map[i][col] < map[i + 1][col]) {
                for (int j = 0; j < L; j++) {
                    if (i - j < 0 || slope[i - j] || map[i][col] != map[i - j][col]) return false;
                    slope[i - j] = true;
                }
            } else {
                for (int j = 1; j <= L; j++) {
                    if (i + j >= N || slope[i + j] || map[i + 1][col] != map[i + j][col]) return false;
                    slope[i + j] = true;
                }
            }
        }
        return true;
    }
}