标签:
标题:剪格子
p1.jpg p2.jpg
如图p1.jpg所示,3 x 3 的格子中填写了一些整数。
我们沿着图中的红色线剪开,得到两个部分,每个部分的数字和都是60。提交时,注意选择所期望的编译器类型。
Thinking:
First of all,you have to realize that the grid which located in the upper left must be a part of the two part divided,thus,we can start DFS from coordinate(0,0).
Detail in the code notes.
#include<iostream> #include<string> #include<algorithm> using namespace std; int visited[10][10]={0},sum=0,direction[4][2]={{-1,0},{0,-1},{1,0},{0,1}},total=0; int row,col,num[10][10]={0},nSeq=0; string reserve[50]; bool judge(int count)//To judge whether the sequence is repeat. { int i,j,k=0,l; for(i=0;i<row;i++) for(j=0;j<col;j++) if(visited[i][j]==1) reserve[nSeq].push_back(i*col+j);//push the coordinate into reserve[] sort(reserve[nSeq].begin(),reserve[nSeq].end());//and sort it smaller to bigger. nSeq++;//nSeq represent n Sequences. if(nSeq!=1)//if nSeq is equal to 1,you dont' have to judge it. { for(l=0;l<nSeq-1;l++) if(reserve[l]==reserve[nSeq-1]) { reserve[nSeq-1].clear(); nSeq--; return false; } } return true; } int minLength()//If the reserve[] have more than 1 sequence,you have to find the shortest sequence. { int i,j,minLen=999; for(i=0;i<nSeq;i++)//easy to understand,no more explains. if(reserve[i].length()<minLen) minLen=reserve[i].length(); return minLen; } void DFS(int x,int y,int count) { int next_x,next_y,i; if(count==sum) { if(judge(count)) total++; return; } else if(count>sum) return; for(i=0;i<4;i++) { next_x=x+direction[i][0]; next_y=y+direction[i][1]; if(next_x<0||next_y<0||next_x>=row||next_y>=col)//boundary condition continue; else if(visited[next_x][next_y]==0)//if the point hasn't been visited. { visited[next_x][next_y]=1;//set the point has been visited. DFS(next_x,next_y,count+num[next_x][next_y]); visited[next_x][next_y]=0;//set the point hasn't been visited. } } } int main() { int i,j; cin>>row>>col; for(i=0;i<row;i++) for(j=0;j<col;j++) { cin>>num[i][j]; sum+=num[i][j]; } if(sum%2!=0)//if sum is odd ,quit. { cout<<"0"<<endl; exit(0); } sum/=2; visited[0][0]=1; DFS(0,0,num[0][0]); if(total!=0)//if the path exist cout<<minLength()<<endl; else cout<<"0"<<endl; return 0; }
标签:
原文地址:http://blog.csdn.net/lc0817/article/details/42833823