首页 > 其他 > 详细

马踏棋盘--dfs

时间:2019-03-02 17:15:26      阅读:195      评论:0      收藏:0      [点我收藏+]

【问题描述】关于马踏棋盘的基本过程:国际象棋的棋盘为 8*8 的方格棋盘。现将"马"放在任意指定的方格中,按照"马"走棋的规则将"马"进行移动。要求每个方格只能进入一次,最终使得"马"走遍棋盘的64个方格。

输入一个n,表示大小为n x n的棋盘

输出马走遍棋盘所有格子的顺序和不同的走法数量

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int vis[10][10];
int cnt = 0, n, m;
int inbord(int x, int y)//判断是否在棋盘上
{
  if (x >= 0 && x<n&&y >= 0 && y<m)
    return 1;
  else
    return 0;
}
void dfs(int x, int y, int ans)
{
  if (inbord(x, y) && !vis[x][y])
  {
    ans++;
    vis[x][y] = ans;
    if (ans == n * m)
    {
      cnt++;
      printf("#case %d\n", cnt);
      for (int i = 0; i < n; i++)
      {
        for (int j = 0; j < m; j++)
          printf("%4d", vis[i][j]);
        printf("\n");
      }
      vis[x][y] = 0;//回溯,遍历不同情况
      return;
    }
    else//八个方向
    {
      dfs(x - 1, y - 2, ans);
      dfs(x - 1, y + 2, ans);
      dfs(x + 1, y - 2, ans);
      dfs(x + 1, y + 2, ans);
      dfs(x + 2, y - 1, ans);
      dfs(x + 2, y + 1, ans);
      dfs(x - 2, y + 1, ans);
      dfs(x - 2, y - 1, ans);
      vis[x][y] = 0;//回溯,一定要走完整个棋盘,要尝试不同方向
    }
  }
  else
    return;
}
int main()
{
  scanf("%d%d", &n, &m);
  memset(vis, 0, sizeof(vis));
  dfs(0, 0, 0);
  return 0;
}

 

马踏棋盘--dfs

原文:https://www.cnblogs.com/-citywall123/p/10461644.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!