!> This file was processed by `fypp`. !> Today's fortune: "forever WJ...", really OK? !> ランダムウォーク猿「'半分全列挙' で はっぴー.」 program f902946 use, intrinsic :: iso_fortran_env !> auto use module implicit none integer(int32), parameter :: dy(*) = [1, 0, -1, 0] integer(int32), parameter :: dx(*) = [0, 1, 0, -1] integer(int32) :: h, w character, allocatable :: grids(:, :) logical, allocatable :: visited(:, :) integer(int32) :: i, j read(input_unit, *) h, w allocate(grids(h, w)) do i = 1, h read(input_unit, '(*(a1))') grids(i, :) end do allocate(visited(h, w), source = .false.) do j = 1, w do i = 1, h if (visited(i, j)) cycle if (grids(i, j) == ".") cycle ! write(error_unit, *) j, i, grids(i, j) block integer(int32) :: cnts character :: first_c cnts = 0 call dfs_count(h, w, grids, visited, cnts, i, j) if (cnts < 4) cycle first_c = grids(i, j) call dfs_fill(h, w, first_c, grids, i, j) end block end do end do do i = 1, h write(output_unit, '(*(a1))') grids(i, :) end do contains pure recursive subroutine dfs_count(h, w, grids, visited, cnts, y, x) integer(int32), intent(in) :: h, w character, intent(in) :: grids(h, w) logical, intent(inout) :: visited(h, w) integer(int32), intent(inout) :: cnts integer(int32), intent(in) :: y, x integer(int32) :: d if (visited(y, x)) return visited(y, x) = .true. cnts = cnts + 1 do d = 1, size(dy) associate(ny => y + dy(d), nx => x + dx(d)) if (ny < 1 .or. ny > h .or. nx < 1 .or. nx > w) cycle if (visited(ny, nx)) cycle if (grids(y, x) /= grids(ny, nx)) cycle call dfs_count(h, w, grids, visited, cnts, ny, nx) end associate end do end subroutine dfs_count pure recursive subroutine dfs_fill(h, w, c, grids, y, x) integer(int32), intent(in) :: h, w character, intent(in) :: c character, intent(inout) :: grids(h, w) integer(int32), intent(in) :: y, x integer(int32) :: d grids(y, x) = "." do d = 1, size(dy) associate(ny => y + dy(d), nx => x + dx(d)) if (ny < 1 .or. ny > h .or. nx < 1 .or. nx > w) cycle if (c /= grids(ny, nx)) cycle call dfs_fill(h, w, c, grids, ny, nx) end associate end do end subroutine dfs_fill end program f902946