Solution :
#include<iostream>
#include<string.h>
using namespace std;
#define INF 2147483640
int min_cost,N,M;
int dataArray[10001][10001];
int visited[10001][10001];
int fx[] = {0,0,1,-1};
int fy[] = {1,-1,0,0};
void calculateMinCost(int sourceX,int sourceY,int destX,int destY,int cost);
void initInputData();
int main()
{
int T,tc,i,j;
freopen("929.txt","r",stdin);
cin >> T;
for(tc=0;tc<T;tc++)
{
cin >> N >> M;
initInputData();
//memset(data,0,sizeof(data));
//memset(visited,false,sizeof(visited));
for(i=0;i<N;i++)
{
for(j=0;j<M;j++)
{
cin >> dataArray[i][j];
}
}
min_cost = INF;
calculateMinCost(0,0,N-1,M-1,dataArray[0][0]);
cout << min_cost << endl;
}
return 0;
}
void calculateMinCost(int sourceX,int sourceY,int destX,int destY,int cost)
{
if(cost > min_cost) return;
if(sourceX == destX && sourceY == destY)
{
if(min_cost > cost)
{
min_cost = cost;
}
return;
}
//below if condition is basically boundary checking
if(sourceX>=0 && sourceY>=0 && sourceX<N && sourceY<M && !visited[sourceX][sourceY] && dataArray[sourceX][sourceY] != INF)
{
int dir;
visited[sourceX][sourceY] = true;
for(dir=0;dir<4;dir++)
{
int dx = sourceX + fx[dir];
int dy = sourceY + fy[dir];
calculateMinCost(dx,dy,destX,destY,cost + dataArray[dx][dy]);
}
visited[sourceX][sourceY] = false;
}
}
void initInputData()
{
int i,j;
for(i=0;i<10001;i++)
{
for(j=0;j<10001;j++)
{
dataArray[i][j] = INF;
visited[i][j] = false;
}
}
}
No comments:
Post a Comment
Thanks for your comments