//拼图游戏随机排列生成算法
// http://www.puke365.cn/puzzle.html
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int m_pos[4][4];
int m_nowx;
int m_nowy;
bool getpos(int nowx,int nowy,int& newx,int& newy,int r)
{
int m = r % 4;
//printf("%d,p/n",m);
if(m == 0)
{
newx = nowx + 1;
newy = nowy;
}
if(m == 1)
{
newx = nowx ;
newy = nowy + 1;
}
if(m == 2)
{
newx = nowx - 1;
newy = nowy;
}
if(m == 3)
{
newx = nowx;
newy = nowy - 1;
}
if(newx >= 4 || newy >=4)
return false;
if(newx < 0 || newy <0)
return false;
return true;
}
int main()
{
int x,y,i=1;
for(y=0;y<4;y++)
{
for(x=0;x<4;x++)
{
m_pos[x][y] = i;
i++;
printf("%d,",m_pos[x][y]);
}
printf("/n");
}
printf("/n");
m_pos[3][3] = 0;
m_nowx = 3;
m_nowy = 3;
srand( (unsigned)time( NULL ) );
int t;
bool b;
int r1 ;
for(i=0;i<200;i++)
{
r1= rand();
//printf( " %6d/n", r1 );
b = getpos(m_nowx,m_nowy,x,y,r1);
if(b)
{
t = m_pos[m_nowx][m_nowy];
m_pos[m_nowx][m_nowy] = m_pos[x][y];
m_pos[x][y] = t;
m_nowx = x;
m_nowy = y;
}
}
for(y=0;y<4;y++)
{
for(x=0;x<4;x++)
{
printf("%d,",m_pos[x][y]);
}
printf("/n");
}
printf("/n");
return 0;
}