Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class N2146 {
- static int input;
- static int[] dx = {-1,1,0,0};
- static int[] dy = {0,0,1,-1};
- static int answer=0;
- static int answer2=Integer.MAX_VALUE;
- static int flag;
- public static final ArrayList<Integer> list = new ArrayList<>();
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner sc = new Scanner(System.in);
- input = sc.nextInt();
- int[][] array = new int[input][input];
- boolean[][] check = new boolean[input][input];
- boolean[][] check2 = new boolean[input][input];
- int[][] dist = new int[input][input];
- int[][] dist2 = new int[input][input];
- Queue<int[]> q = new LinkedList<int[]>();
- int count=0;
- //int answer =0;
- for(int i=0; i<input; i++) {
- for(int t=0; t<input; t++) {
- array[i][t] = sc.nextInt();
- }
- }
- //섬 영역 구하기
- for(int i=0; i<input; i++) {
- for(int k=0; k<input ; k++) {
- if(array[i][k]==1 && check[i][k]==false ) {
- bfs(array, count+=1, check, dist, i, k);
- }
- }
- }
- for(int i=0; i<input; i++) {
- for(int k=0; k<input ; k++) {
- if(dist[i][k]!=0) {
- q.offer(new int[] {i,k});
- }
- }
- }
- test( dist2, answer2, check2, dist, q);
- for(int v : list) {
- if (answer2 > v) {
- answer2 = v;
- }
- }
- // System.out.println(list);
- //
- // for(int i=0; i<input; i++) {
- // for(int k=0; k<input ; k++) {
- // System.out.print(dist2[i][k]);
- // if(k==input-1) System.out.println("");
- // }
- // }
- System.out.println(answer2);
- }
- static void bfs(int[][] array, int count, boolean[][] check, int[][] dist, int x, int y) {
- Queue<int[]> q = new LinkedList<int[]>();
- q.offer(new int[] {x,y});
- check[x][y] = true;
- dist[x][y] = count;
- while(!q.isEmpty()) {
- int[] head = q.poll();
- for(int i=0; i<4; i++) {
- int nx = head[0] + dx[i];
- int ny = head[1] + dy[i];
- if(nx>=0 && ny>=0 && nx<input && ny<input) {
- if(array[nx][ny]==1 && check[nx][ny] == false) {
- bfs(array,count,check,dist,nx,ny);
- }
- }
- }
- }
- }
- static void test(int[][] array, int answer, boolean[][] check2, int[][] dist, Queue<int[]> q) {
- Loop : while(!q.isEmpty()) {
- int[] head = q.poll();
- for(int i=0; i<4; i++) {
- int nx = head[0] + dx[i];
- int ny = head[1] + dy[i];
- if(nx>=0 && ny>=0 && nx<input && ny<input) {
- if(dist[nx][ny]!=0 && dist[nx][ny] != dist[head[0]][head[1]]) {
- list.add(array[nx][ny] + array[head[0]][head[1]]);
- // System.out.println("nx : "+nx + " ny" + ny + " head " + head[0] + " hhh" + head[1]);
- // System.out.println(array[nx][ny] +" " + array[head[0]][head[1]]);
- }
- if(dist[nx][ny]==0 ) {
- q.offer(new int[] {nx,ny});
- dist[nx][ny] = dist[head[0]][head[1]];
- array[nx][ny] = array[head[0]][head[1]]+1;
- //test(array,answer++,check2,dist,nx,ny);
- }
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment