알고리즘 공부/문제 풀이

[JAVA] SWEA 4014 활주로 건설

valid_ming 2021. 10. 6. 17:03

문제 링크

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

문제 설명은 링크를 이용해주세요.

 

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

public class Solution {

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int T = Integer.parseInt(br.readLine());
		
		for(int t=1; t<=T; t++) {
			StringTokenizer st = new StringTokenizer(br.readLine());
			int N = Integer.parseInt(st.nextToken());
			int X = Integer.parseInt(st.nextToken());
			
			int[][] 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 ans = 0;
			
			next: for(int i=0; i<N;i++) {
				int cnt = 1;
				boolean down = false;
				
				for(int j=1; j<N;j++) {
					if(map[i][j-1]==map[i][j]) cnt++;
					else if(map[i][j-1]+1==map[i][j]) { //오르막, 이전의 개수 확인
						if(down && cnt<2*X) continue next;
						if(!down && cnt<X) continue next;
						down = false;
						cnt = 1;
					}
					else if(map[i][j-1]-1==map[i][j]) { //내리막, 이후 개수 확인
						if(down && cnt<X) continue next;
						down = true;
						cnt = 1;
					}
					else continue next;
				}
				
				if(!down || down && cnt>=X) ans++;
			}
			
			next: for(int i=0; i<N;i++) {
				int cnt = 1;
				boolean down = false;
				
				for(int j=1; j<N;j++) {
					if(map[j-1][i]==map[j][i]) cnt++;
					else if(map[j-1][i]+1==map[j][i]) { //오르막, 이전의 개수 확인
						if(down && cnt<2*X) continue next;
						if(!down && cnt<X) continue next;
						down = false;
						cnt = 1;
					}
					else if(map[j-1][i]-1==map[j][i]) { //내리막, 이후 개수 확인
						if(down && cnt<X) continue next;
						down = true;
						cnt = 1;
					}
					else continue next;
				}
				
				if(!down || down && cnt>=X) ans++;
			}
			
			System.out.println("#"+t+" "+ans);
		}

	}

}