문제풀기 : [백준14890 경사로]
package sw;
import java.io.*;
public class Main14890_경사로 {
static int N,L;
static int[][] map;
static boolean check(int x, int y) {
if(x>=0 && x<map.length && y>=0 && y<map[x].length)
return true;
else return false;
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().trim().split(" ");
N = Integer.parseInt(input[0]);
L = Integer.parseInt(input[1]);
map = new int[N][N];
for(int i=0; i<N; i++) {
input = br.readLine().trim().split(" ");
for(int j=0; j<N; j++) {
map[i][j] = Integer.parseInt(input[j]);
}
}
int res = 0;
int state, direct;
boolean canWay;
boolean visit[];
for(int i=0; i<N; i++) {
state = 0;
direct = 0;
canWay = true;
visit = new boolean[N];
for(int j=1; j<N; j++) {
state = checkUpAndDown(i,j,direct);
if(state == -1) {
canWay = canWay(i,j,direct,state, visit);
}else if(state == 1) {
canWay = canWay(i,j,direct,state, visit);
}else if(state == 0) {
continue;
}else canWay = false;
if(!canWay) break;
if(state == -1) j+=(L-1);
}
if(canWay) res++;
}
for(int j=0; j<N; j++) {
state = 0;
direct = 1;
canWay = true;
visit = new boolean[N];
for(int i=1; i<N; i++) {
state = checkUpAndDown(i,j,direct);
if(state == -1) {
canWay = canWay(i,j,direct,state,visit);
}else if(state == 1) {
canWay = canWay(i,j,direct,state,visit);
}else if(state == 0) {
continue;
}else canWay = false;
if(!canWay) break;
if(state == -1) i+=(L-1);
}
if(canWay) res++;
}
System.out.println(res);
}
/*
* return
* -1: down
* 1 : up
* 0 : flat
* -2 : false
*/
static int checkUpAndDown(int x, int y, int d) {
if(d==0) {
if(map[x][y] - map[x][y-1] == -1) {
return -1;
}else if(map[x][y] - map[x][y-1] == 1) {
return 1;
}else if(map[x][y] == map[x][y-1]) {
return 0;
}else return -2;
}else {
if(map[x][y] - map[x-1][y] == -1) {
return -1;
}else if(map[x][y] - map[x-1][y] == 1) {
return 1;
}else if(map[x][y] == map[x-1][y]) {
return 0;
}else return -2;
}
}
// d==1 우, d==0 하
static boolean canWay(int x, int y, int d, int state, boolean[] visit) {
if(d == 0) {
if(state == -1) {
int h = map[x][y];
for(int j=y; j<y+L; j++) {
if(!check(x,j) || map[x][j] != h) return false;
if(visit[j]) return false;
visit[j] = true;
}
}else if(state == 1) {
int h = map[x][y-1];
for(int j=y-1; j>=y-L; j--) {
if(!check(x,j) || map[x][j] != h) return false;
if(visit[j]) return false;
visit[j] = true;
}
}
}else if(d == 1) {
if(state == -1) {
int h = map[x][y];
for(int i=x; i<x+L; i++) {
if(!check(i,y) || map[i][y] != h) return false;
if(visit[i]) return false;
visit[i] = true;
}
}else if(state == 1) {
int h = map[x-1][y];
for(int i=x-1; i>=x-L; i--) {
if(!check(i,y) || map[i][y] != h) return false;
if(visit[i]) return false;
visit[i] = true;
}
}
}
return true;
}
}
PREVIOUS[삼성기출]백준14891 - 톱니바퀴
NEXT[삼성기출]백준3190 - 뱀