프로 그래 밍 - 행렬 왼쪽 상단 에서 오른쪽 하단 으로
# include
# include
using namespace std;
void getPath(vector<vector<int> > &matrix, int &value, vector<int> &path_i, vector<int> &path_j)
{
if(matrix.empty())
return;
int rows = matrix.size();
int cols = matrix[0].size();
vector<vector<int> > stat(rows, vector<int> (cols)); //
vector<vector<int> > direct(rows, vector<int> (cols)); // (1 ,0 ))
int sum = 0;
for (int j = 0; j < cols; ++j) //
{
sum += matrix[0][j];
stat[0][j] = sum;
direct[0][j] = 1;
}
sum = 0;
for (int i = 0; i < rows; ++i) //
{
sum += matrix[i][0];
stat[i][0] = sum;
direct[i][0] = 0;
}
for (int i = 1; i < rows; ++i) //
{
for (int j = 1; j < cols; ++j)
{
if (stat[i - 1][j] < stat[i][j - 1])
{
stat[i][j] = stat[i - 1][j] + matrix[i][j];
direct[i][j] = 0;
}
else
{
stat[i][j] = stat[i][j - 1] + matrix[i][j];
direct[i][j] = 1;
}
}
}
value = stat[rows - 1][cols - 1]; //
for (int i = rows -1, j = cols - 1; i >= 0 && j >= 0;) //
{
path_i.push_back(i);
path_j.push_back(j);
if (direct[i][j] == 1)
j--;
else
i--;
}
}
void printPath(vector<int> path_i, vector<int> path_j) //
{
for (int i = path_i.size() - 1; i >= 0; --i)
{
cout << '(' << path_i[i] << ", " << path_j[i] << ')' << endl;
}
}
int main(void)
{
int matrix_temp[6][7] = {{0, 2, 8, 3, 7, 9, 6},
{5, 3, 7, 9, 6, 8, 1},
{3, 9, 2, 9, 8, 7, 6},
{8, 8, 1, 6, 9, 6, 8},
{3, 2, 9, 8, 7, 7, 1},
{4, 2, 9, 6, 5, 3, 9}};
vector<vector<int> > matrix;
int rows = 6;
int cols = 7;
for (int i = 0; i < rows; ++i)
{
vector<int> temp;
for (int j = 0; j < cols; ++j)
{
temp.push_back(matrix_temp[i][j]);
}
matrix.push_back(temp);
temp.clear();
}
vector<int> path_i; //
vector<int> path_j; //
int value; //
getPath(matrix, value, path_i, path_j);
cout << "value is " << value << endl;
cout << "path: " << endl;
printPath(path_i, path_j);
}
잘못된 점 이 있 으 면 지적 하여 바로잡아 주 십시오.