preternatural

马的棋盘遍历

一个方棋盘(当然也可以是矩形的,这里我主要是为了声明数组方便把它定义成方棋盘),上面有一只马,打印出它走过这些所有位置各一次的全部可能走法。使用的是递归,没有用回溯。

#include "stdafx.h"
#include 
<iomanip>
using namespace std;

void Hanmilton(int* a, int* b, int n, int i, int j, int progress)
{
    
/*if (a[i * n + j])
    {
        return;
    }
*/

    
for (int x = 0; x < progress - 1; x++)
    
{
        
if (b[x] == i * n + j)
        
{
            
return;
        }

    }


    a[i 
* n + j] = progress;
    b[progress 
- 1= i * n + j;
    
if (progress >= n * n)
    
{
        
for (int x = 0; x < n; x++)
        
{
            
for (int y = 0; y < n; y++)
            
{
                cout 
<< setw(3<< a[x * n + y];
            }

            cout 
<< endl;
        }

        cout 
<< "=========end=======" << endl;
        cout 
<< "\n===================" << endl;

        
return;
    }


    
if (i + 1 < n)
    
{
        
if (j + 2 < n)
        
{
            Hanmilton(a, b, n, i
+1, j+2, progress + 1);
        }

        
if (j - 2 >= 0)
        
{
            Hanmilton(a, b, n, i
+1, j-2, progress + 1);
        }

    }

    
if (i - 1 >=0)
    
{
        
if (j + 2 < n)
        
{
            Hanmilton(a, b, n, i
-1, j+2, progress + 1);
        }

        
if (j - 2 >= 0)
        
{
            Hanmilton(a, b, n, i
-1, j-2, progress + 1);
        }

    }


    
if (i + 2 < n)
    
{
        
if (j + 1 < n)
        
{
            Hanmilton(a, b, n, i
+2, j+1, progress + 1);
        }

        
if (j - 1 >= 0)
        
{
            Hanmilton(a, b, n, i
+2, j-1, progress + 1);
        }

    }

    
if (i - 2 >= 0)
    
{
        
if (j + 1 < n)
        
{
            Hanmilton(a, b, n, i
-2, j+1, progress + 1);
        }

        
if (j - 1 >= 0)
        
{
            Hanmilton(a, b, n, i
-2, j-1, progress + 1);
        }

    }

}


int _tmain(int argc, _TCHAR* argv[])
{
    
int n;
    cin 
>> n;

    
int* a = new int[n * n];//访问序号
    int* b = new int[n * n];//访问序列
    for (int i = 0; i < n * n; i++)
    
{
        a[i] 
= 0;
        b[i] 
= -1;
    }

    cout 
<< setw(3);
    Hanmilton(a, b, n, 
001);

    
return 0;
}

posted on 2007-08-01 20:51  preternatural  阅读(549)  评论(0编辑  收藏  举报

导航