Seam Carving
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1353 Accepted Submission(s): 532
For an original image G of m*n, where m and n are the row and column of the image respectively. Fish obtained the corresponding energy matrix A. He knew every time a seam with the lowest energy should be carved. That is, the line with the lowest sum of energy passing through the pixels along the line, which is a 8-connected path vertically or horizontally.
Here your task is to carve a pixel from the first row to the final row along the seam. We call such seam a vertical seam.
也是一道非常簡單的遞歸題,注意要最右面的答案就可以了,我單獨設置了一個數組存路徑,其實直接回推也是可以的
#include <bits/stdc++.h>
using namespace std;
int main()
{
int T,m,n,a[105][105],sum[105][105],ans[105][105],num,wei,hah[105],cur;
cin>>T;
for(int k=1;k<=T;k++)
{
cin>>m>>n;
memset(sum,0x3f3f3f,sizeof(sum));
for(int i=1;i<=m;i++)
for(int j=1;j<=n;j++)
cin>>a[i][j];
for(int i=1;i<=n;i++)
{
sum[1][i]=a[1][i];
ans[i][1]=1;
}
for(int i=2;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
if(sum[i-1][j+1]<=sum[i-1][j-1]&&sum[i-1][j+1]<=sum[i-1][j])
{
sum[i][j]=sum[i-1][j+1]+a[i][j];
ans[i][j]=j+1;
}
else if(sum[i-1][j]<=sum[i-1][j+1]&&sum[i-1][j]<=sum[i-1][j-1])
{
sum[i][j]=sum[i-1][j]+a[i][j];
ans[i][j]=j;
}
else
{
sum[i][j]=sum[i-1][j-1]+a[i][j];
ans[i][j]=j-1;
}
}
}
num=0x3f3f3f;
for(int i=n;i>=1;i--)
{
if(sum[m][i]<num)
{
num=sum[m][i];
wei=i;
}
}
//cout<<num<<endl;
cout<<"Case "<<k<<endl;
cur=0;
for(int i=m;i>=1;i--)
{
hah[cur++]=wei;
wei=ans[i][wei];
}
for(int i=cur-1;i>0;i--)
cout<<hah[i]<<" ";
cout<<hah[0]<<endl;
}
return 0;
}