Description
New game是在一个M*M的特殊棋盘(棋盘的第i行都标上了数字i)上进行的新式游戏。给定一个数字N,要求选手把一个棋子从左上角(1,1)移到右下角(M,M),移动时只能往右或往下。要求移动后经过的数字和为N,且拐弯的次数最少。
如果对给出的N,选手不能找出移动方案使得经过的数字和为N或找出的路径拐弯次数不是最少,选手就输了。所以,选手一定千方百计要找出满足条件的路径!!
Input
两个正整数M,N(其中M<=16),数据保证有解。
Output
最少拐弯数。
Sample
Input
4 22
Output
1
#include <iostream>
#include<bits/stdc++.h>
#define Max 0x3f3f3f3f
using namespace std;
bool vis[35][35];
int Map[35][35];
int X[] = {1,0};
int Y[] = {0,1};
int Min_step;
int n,m;
void DFS(int x,int y,int flag,int id,int cnt)
{
if(id > Min_step)
return ;
if(cnt > n)
return ;
if(x == m && y ==m)
{
if(cnt == n)
Min_step = min(Min_step, id);
return ;
}
for(int i=0;i<2;i++)
{
int dx = x + X[i];
int dy = y + Y[i];
if(dx >= 1 && dx <=m && dy >= 1 && dy <= m && !vis[dx][dy])
{
vis[dx][dy] = true;
if(cnt == 1)
DFS(dx,dy,i,id,cnt+Map[dx][dy]);
else
{
if(i != flag)
DFS(dx,dy,i,id+1,cnt+Map[dx][dy]);
else
DFS(dx,dy,i,id,cnt+Map[dx][dy]);
}
vis[dx][dy] = false;
}
}
}
int main ()
{
while(cin>>m>>n)
{
memset(vis,false,sizeof(vis));
Min_step = Max;
for(int i=1;i<=m;i++)
for(int j=1;j<=m;j++)
Map[i][j] = i;
vis[1][1] = true;
DFS(1, 1, 0, 0, 1);
cout<<Min_step<<endl;
}
return 0;
}