알고리즘

백준 11123번 양한마리 양두마리 (JAVA)

박카스마시며코딩 2022. 8. 19. 22:25

https://www.acmicpc.net/problem/11123

 

11123번: 양 한마리... 양 두마리...

얼마전에 나는 불면증에 시달렸지... 천장이 뚫어져라 뜬 눈으로 밤을 지새우곤 했었지.  그러던 어느 날 내 친구 광민이에게 나의 불면증에 대해 말했더니 이렇게 말하더군. "양이라도 세봐!"  

www.acmicpc.net

 

저는 해당 문제를 BFS를 통해 해결하였습니다.

방문하지 않은 곳에 BFS를 하여 방문 체크를 하면서 무리의 개수를 확인하였습니다.

 

package BOJ.bfs;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
import java.util.function.Function;

public class BOJ_11123 {
    private static final char SHEEP = '#';
    private static final char EMPTY = '.';


    public static void main(String[] args) throws Exception {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        Function<String,Integer> stoi = Integer::parseInt;
        int testCnt = stoi.apply(st.nextToken());
        for(int t = 0 ; t < testCnt ; t++){
            st = new StringTokenizer(br.readLine());
            int n = stoi.apply(st.nextToken());
            int m = stoi.apply(st.nextToken());
            char[][] map = new char[n][m];
            for(int i = 0 ; i < n ; i++){
                String command = br.readLine();
                for(int j = 0 ; j < m ; j++){
                    map[i][j] = command.charAt(j);
                }
            }
            int result = 0;
            boolean[][] visited = new boolean[n][m];
            for(int i = 0 ; i < n ; i++){
                for(int j = 0 ; j < m ; j++){
                    if(!visited[i][j] && map[i][j] == SHEEP){
                        bfs(i,j,map,visited,n,m);
                        result++;
                    }
                }
            }
            System.out.println(result);
        }
    }
    private static final int[] DY = {-1,0,1,0};
    private static final int[] DX = {0,1,0,-1};
    private static void bfs(int y, int x, char[][] map, boolean[][] visited,int n,int m) {
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[] {y,x});
        visited[y][x] = true;
        while(!q.isEmpty()){
             int[] now = q.poll();
             for(int i = 0 ; i < 4; i++){
                 int ny = now[0] + DY[i];
                 int nx = now[1] + DX[i];
                 if(checkBound(ny,nx,n,m) && map[ny][nx] == SHEEP && !visited[ny][nx]){
                     q.offer(new int[] {ny,nx});
                     visited[ny][nx] = true;
                 }
             }
        }
    }

    private static boolean checkBound(int ny, int nx, int n, int m) {
        if( ny >= 0 && ny < n && nx >= 0 && nx < m){
            return true;
        }
        return false;
    }
}

'알고리즘' 카테고리의 다른 글

백준 1337번 올바른 배열 (JAVA)  (0) 2022.08.21
백준 21938번 영상처리 (JAVA)  (0) 2022.08.20
백준 21937번 작업 (JAVA)  (0) 2022.08.18
백준 24463번 미로 (JAVA)  (0) 2022.08.17
백준 17404번 RGB거리2 (JAVA)  (0) 2022.08.16