배꼽파지 않도록 잘 개발해요

99클럽 코테 스터디 31일차 TIL - 양 한마리 본문

코딩테스트/99클럽

99클럽 코테 스터디 31일차 TIL - 양 한마리

꼽파 2024. 8. 24. 23:13


function countSheepGroups(grid, H, W) {
    const directions = [
        [-1, 0], [1, 0], [0, -1], [0, 1]
    ];

    function dfs(x, y) {
        if (x < 0 || x >= H || y < 0 || y >= W) return;
        if (grid[x][y] !== '#') return;

        grid[x][y] = '.';

        for (let [dx, dy] of directions) {
            dfs(x + dx, y + dy);
        }
    }

    let sheepGroupCount = 0;

    for (let i = 0; i < H; i++) {
        for (let j = 0; j < W; j++) {
            if (grid[i][j] === '#') {
                sheepGroupCount++;
                dfs(i, j);
            }
        }
    }

    return sheepGroupCount;
}

function solve(input) {
    try {
        const lines = input.trim().split('\n');
        let idx = 0;
        const T = parseInt(lines[idx++]);
        const results = [];

        for (let t = 0; t < T; t++) {
            const [H, W] = lines[idx++].split(' ').map(Number);

            // H나 W가 0이면 양 무리는 0개
            if (H === 0 || W === 0) {
                results.push(0);
                continue;
            }

            const grid = [];
            for (let i = 0; i < H; i++) {
                grid.push(lines[idx++].split(''));
            }

            results.push(countSheepGroups(grid, H, W));
        }

        // 최종적으로 한 번에 출력
        console.log(results.join('\n'));
    } catch (error) {
        console.error("An error occurred:", error.message);
    }
}

// 예제 입력
const input = `2
4 4
#.#.
.#.#
#.##
.#.#
3 5
###.#
..#..
#.###`;

solve(input);
728x90