program yukicoder_401 use, intrinsic :: iso_fortran_env implicit none integer(int32) :: n, y, x, next_y, next_x, direction integer(int32), allocatable :: grids(:, :) integer(int32) :: i read(input_unit, *) n allocate(grids(0:n+1, 0:n+1), source = -1) grids(0, :) = huge(0_int32) grids(:, 0) = huge(0_int32) grids(n + 1, :) = huge(0_int32) grids(:, n + 1) = huge(0_int32) y = 1; x = 1 direction = 1 do i = 1, n * n grids(y, x) = i ! write(error_unit, *) grids(1:n, 1:n) select case(direction) case(1) !> EAST. if (grids(y, x + 1) > 0) then direction = 2 y = y + 1 else x = x + 1 end if case(2) !> SOUTH. if (grids(y + 1, x) > 0) then direction = 3 x = x - 1 else y = y + 1 end if case(3) !> WEST. if (grids(y, x - 1) > 0) then direction = 4 y = y - 1 else x = x - 1 end if case(4) !> NORTH. if (grids(y - 1, x) > 0) then direction = 1 x = x + 1 else y = y - 1 end if end select end do do i = 1, n write(output_unit, '(*(i3.3, 1x))') grids(i, 1:n) end do end program yukicoder_401