재귀함수(Recursive function)를 이용한 프로그램 작성

도로 경로 개수 구하기

PROGRAM Path_Counter

IMPLICIT NONE

INTEGER :: StartRow, StartCol, EndRow, EndCol

PRINT *, "시작 좌표를 입력하시오(ex:2, 3)"
READ *, StartRow, StartCol

PRINT *, "종료 좌표를 입력하시오(ex, 4, 6)"
READ *, EndRow, EndCol

PRINT *, "시작 지점에서 종료 지점까지 가는 경로는", Number_of_Paths(EndRow - StartRow, EndCol - StartCol), " 개 입니다"

CONTAINS

RECURSIVE FUNCTION Number_of_Paths(NumRows, NumCols) RESULT (Num_Paths)

INTEGER, INTENT(IN) :: NumRows, NumCols
INTEGER :: Num_Paths

IF ( (NumRows == 0) .OR. (NumCols == 0) ) THEN
Num_Paths = 1
ELSE
Num_Paths = Number_of_Paths(NumRows - 1, NumCols) + Number_of_Paths(NumRows, NumCols -1)
END IF

END FUNCTION Number_of_Paths

END PROGRAM Path_Counter

위 소스를 06_09_Path_Counter.f95로 저장

컴파일 및 프로그램 테스트



+ Recent posts