티스토리 뷰

공부 이야기

[C] MatrixPath

판다(panda) 2009. 11. 15. 00:03

// MatrixPath.cpp : 콘솔 응용 프로그램에 대한 진입점을 정의합니다.
//



#include "stdafx.h"

#define COLS 11
#define ROWS 10

// #define MIN(X,Y) (((X)<(Y))?(X):(Y))
int min(int x, int y)
{

 return x<y?x:y;

}

int count = 0;

int mPath(int m[][COLS], int x, int y)
{

 count++;
 if( x == 0 && y == 0 )

return m[0][0];

 if( x == 0 )

return m[y][0]+mPath(m, 0, y-1);

 if( y == 0 )

return m[0][x]+mPath(m, x-1, 0);

 return m[y][x] + min(mPath(m, x-1, y), mPath(m, x, y-1));

}

int _tmain(int argc, _TCHAR* argv[])
{

 int m[ROWS][COLS] =
 {

  { 1, 1, 1, 2, 1, 3, 2, 1, 2, 1, 2 },
  { 2, 3, 1, 4, 2, 4, 1, 3, 1, 2, 2 },
  { 1, 7, 1, 1, 2, 1, 2, 1, 2, 1, 1 },
  { 2, 1, 3, 1, 2, 1, 1, 3, 1, 2, 2 },
  { 1, 1, 1, 2, 1, 3, 2, 1, 2, 1, 2 },
  { 2, 3, 1, 4, 2, 4, 1, 3, 1, 2, 2 },
  { 1, 7, 1, 1, 2, 1, 2, 1, 2, 1, 1 },
  { 2, 1, 3, 1, 2, 1, 1, 3, 1, 2, 2 },
  { 1, 1, 1, 2, 1, 3, 2, 1, 2, 1, 2 },
  { 1, 7, 1, 1, 2, 1, 2, 1, 2, 1, 1 }

 
 };

 printf("Minium matrix path = %d\n", mPath(m, COLS-1, ROWS-1));
 printf("Count = %d\n", count);
 return 0;

}

실행결과