////
Search
Duplicate
💯

[SWEA] 격자판 칠하기 (JAVA 자바)

생성일
2022/11/16 13:19
태그
import java.util.LinkedList; import java.util.Queue; import java.util.Scanner; import java.io.FileInputStream; class Solution { static char[][] arr; static boolean[][] visited; static int N; static int M; static int[] dx = {1,-1,0,0}; static int[] dy = {0,0,1,-1}; //아래,위, 오른쪽, 왼쪽 public static void main(String args[]) throws Exception { Scanner sc = new Scanner(System.in); int T; T=sc.nextInt(); for(int test_case = 1; test_case <= T; test_case++) { N = sc.nextInt(); M = sc.nextInt(); arr = new char[N][M]; visited = new boolean[N][M]; for(int i=0;i<N;i++){ String s = sc.next(); for(int j=0;j<M;j++){ arr[i][j] = s.charAt(j); visited[i][j]=false; } } int result = bfs(); if(result == 1){ System.out.println("#"+test_case+" possible"); }else{ System.out.println("#"+test_case+" impossible"); } } } public static int bfs(){ Queue<Node> queue = new LinkedList<>(); queue.add(new Node(0,0,arr[0][0])); visited[0][0] = true; while(!queue.isEmpty()){ // 큐가 빌 때까지 반복문을 돌림 Node node = queue.poll(); // 큐에서 가장 먼저 들어간 Node를 꺼냄 char color = node.color; for(int i=0;i<4;i++){ //for 문을 4번 돌려주는 이유는 dx dy의 크기만큼 돌려주는것인데 dx, dy 는 현재 좌표에서 위, 아래, 오른쪽, 왼쪽으로 욺직여주기 위해서이다. // 이렇게 그냥 돌리게 되면 물론 Outofbound 에러가 뜨겠지만 아래에서 예외 처리를 해준다. int newX = node.x+ dx[i]; // newX 에다가 dx 를 newY 에다가 dy를 더해줌 그럼 좌표가 아래든 위든 오른쪽이든 왼쪽이든 바뀜 int newY = node.y+ dy[i]; if(newX>=0&&newX<N&&newY>=0&&newY<M&&visited[newX][newY]==false){ //여기가 outOfBound 에러의 예외처리 char newColor = arr[newX][newY]; if(color!='?'&&newColor==color){ //여기서 부터 마지막 까지 다 조건: 양옆에 같은게 있으면 -1을 반환 해서 impossible을 출력하게함 return -1; } else if(color=='#'&&newColor=='.'){ visited[newX][newY] = true; queue.add(new Node(newX,newY,newColor)); } else if(color=='#'&&newColor=='?'){ newColor = '.'; visited[newX][newY] = true; queue.add(new Node(newX,newY,newColor)); } else if(color=='.'&&newColor=='#'){ visited[newX][newY] = true; queue.add(new Node(newX,newY,newColor)); } else if(color=='.'&&newColor=='?'){ newColor = '#'; visited[newX][newY] = true; queue.add(new Node(newX,newY,newColor)); } else if(color=='?'&&newColor=='.'){ color = '#'; visited[newX][newY] = true; queue.add(new Node(newX,newY,newColor)); } else if (color =='?' && newColor == '#') { color = '.'; visited[newX][newY] = true; queue.add(new Node(newX,newY,newColor)); } else if(color=='?'&&newColor =='?'){ visited[newX][newY] =true; queue.add(new Node(newX,newY,newColor)); } } } } return 1; } public static class Node{ //노드를 쓰는 이유는 아래에서 int x; int y; char color; Node(int x, int y,char color){ this.x=x; this.y=y; this.color = color; } } }
Java
복사
노드 클래스를 만들어서 쓰는 이유는 큐에 x,y,color 를 넣어야한다. 좌표를 바꿔가며 색깔을 검사하기 위해서 이것들을 넣는데 이걸 편하게 넣고 빼 쓰기 위해서 Node클래스를 만든다. 다른 방법이 있는지는 잘모르겠다.
자세한 코드내용은 주석을 보면 이해할 수 있다.