공부기록/백준

[백준] 3184번 양

메델 2024. 2. 13. 06:38
import java.util.Scanner;

public class Main {
    
    static int R, C;
    static char[][] map;
    static int sheepCount, wolfCount, totalSheep, totalWolf;
    static int[] dx = {1, 0, -1, 0};
    static int[] dy = {0, 1, 0, -1};
    static boolean[][] visited;
    static StringBuilder sb = new StringBuilder(); 
    
    static void dfs(int x, int y) {
        visited[x][y] = true;
        if(map[x][y] == 'o') sheepCount++;
        if(map[x][y] == 'v') wolfCount++;
        
        for(int i=0; i<4; i++) {
            int nx = x + dx[i];
            int ny = y + dy[i];
            
            if(nx < 0 || nx >= R || ny < 0 || ny >= C) continue;
            if(map[nx][ny] == '#') continue;
            if(visited[nx][ny]) continue;
            dfs(nx, ny);
        }
    }
    
    public static void main(String[] args) {
        
        Scanner kb = new Scanner(System.in);
        
        R = kb.nextInt();
        C = kb.nextInt();
        
        map = new char[R][C];
        visited = new boolean[R][C];
        
        for(int i = 0; i < R; i++) {
            map[i] = kb.next().toCharArray();
        }
        
        for(int i = 0; i < R; i++) {
            for(int j = 0; j < C; j++) {
                if(!visited[i][j] && map[i][j] != '#') {
                    sheepCount = 0; 
                    wolfCount = 0;
                    dfs(i, j);
                    if(sheepCount > wolfCount) {
                        totalSheep += sheepCount;
                    } else {
                        totalWolf += wolfCount;
                    }
                }
            }
        }
        sb.append(totalSheep).append(' ').append(totalWolf);
        System.out.println(sb.toString());
        
    }
}

'공부기록 > 백준' 카테고리의 다른 글

[백준] 19637번 IF문 좀 대신 써줘  (0) 2024.03.24
[백준] 1927번 최소 힙  (0) 2024.02.15
[백준] 9461번 파도반 수열  (1) 2024.02.13
[백준] 1822번 차집합  (1) 2024.02.13
[백준] 1436번 영화감독 숌  (1) 2024.02.08