알고리즘 문제 질문드립니다.
조회수 609회
안녕하세요! 새내기라서 처음 질문해보네요:) 알고리즘 공부를 하고 있는데 사이트에서 계속 답이 틀렸다고 나와서 혹시 제 코드를 한번 봐 주실 수 있는지 요청드리고 싶습니다. https://www.acmicpc.net/problem/16234
위 사이트가 문제 사이트 이구요, 제 코드는 다음과 같습니다. 도움 부탁드립니다. 감사합니다.!!
import java.util.Scanner;
public class Main {
static int n;
static int l;
static int r;
static int cpt = 0;
static int [] cpn;
static int [] cpn_num ;
static int[][] A;
static int[][] B;
static int[][] M;
static int sec = 0;
static boolean[][] visited;
static int flags = 0;
static int[] x = {-1, 0, 1, 0};
static int[] y = {0, 1, 0, -1};
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
n = scan.nextInt();
l = scan.nextInt();
r = scan.nextInt();
A = new int[n][n];
B = new int[n][n];
M = new int[n][n];
cpn = new int[n*n+1];
cpn_num = new int[n*n+1];
visited = new boolean[n][n];
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
A[i][j] = scan.nextInt();
B[i][j] = A[i][j];
M[i][j] = A[i][j];
}
}
while(true){
flags = 0;
cpt = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(!visited[i][j]){
cpt++;
dfs(i, j, cpt);
change(cpt);
}
}
}
if(compare() == 1){
break;
}else{
sec++;
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
M[i][j] = A[i][j];
visited[i][j] = false;
B[i][j] = A[i][j];
}
}
cpn = new int[n*n+1];
cpn_num = new int[n*n+1];
}
}
System.out.println(sec);
}
public static void change(int flag){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(B[i][j] == flag){
A[i][j] = cpn[flag]/cpn_num[flag];
}
}
}
}
public static int compare(){
for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
if(A[i][j] != M[i][j]){
return 0;
}
}
}
return 1;
}
public static void dfs(int a, int b, int cpt){
visited[a][b] = true;
B[a][b] = cpt;
cpn[cpt] = cpn[cpt] + A[a][b];
cpn_num[cpt]++;
for(int i = 0; i < 4; i++){
int nx = a + x[i];
int ny = b + y[i];
if(nx < 0 || ny < 0 || nx >= n || ny >= n){
continue;
}
int diff = Math.abs(A[a][b] - A[nx][ny]);
if(l <= diff && diff <= r && !visited[nx][ny]){
dfs(nx, ny, cpt);
}
}
}
}
-
(•́ ✖ •̀)
알 수 없는 사용자
댓글 입력