【MATLAB编程实例练习】-(30)Knight‘s Tour Checker(马走日)

题目:

来源于Mathwork上的Cody,Problem 96 - Knight’s Tour Checker,
Given a matrix a, determine whether or not a legal knight’s tour is present. The knight’s tour always follows the pattern 1, 2, 3, … but it need not fill the entire matrix. Any unused squares contain zeros. Your function should return true if the counting sequence from 1 to n represents a knight’s tour, and false if not.
Example
The matrix a as given below is a legal knight’s tour. The middle square is unreachable, but since it contains a zero, it satisfies the condition. The function should return TRUE.
7 2 5
4 0 8
1 6 3
Here is another legal (if short) knight’s tour. The test suite will always contain at least one move (i.e. the counting sequence [1 2]). Note the matrix is not required to be square.
1 0 0
0 0 2
Here is an illegal knight’s tour. Everything is fine up until the jump from 14 to 15, which is illegal because it jumps from row 4 to row 1.
15 5 12 3
0 2 9 6
8 11 4 13
1 14 7 10

代码

function tf = knights_tour(a)
  %tf = true;
  max_a=max(max(a));
  for i=1:max_a-1
      [row_1,col_1] = find(a==i);
      [row_2,col_2] = find(a==i+1);
      if abs(row_2-row_1)*abs(col_2-col_1)==2
          tf = true;
      else
          tf = false;
          break;
      end
  end
end

测试

>> clear;a =[ 7     2     5;4     0     8;1     6     3];knights_tour(a)

ans =

  logical

   1
>> clear;a = ...
[ 1     0   0
  0     0   2];knights_tour(a)

ans =

  logical

   1
>> clear;a =[ 7     2     5;4     0     8;1     6     3];knights_tour(a)

ans =

  logical

   1
>> clear;a = ...
[ 15     5    12     3
   0     2     9     6
   8    11     4    13
   1    14     7    10];knights_tour(a)

ans =

  logical

   0
>> clear;a = ...
[  0     5    12     3
  15     2     9     6
   8    11     4    13
   1    14     7    10];knights_tour(a)

ans =

  logical

   1
>> clear;a = [22 29 4 31 16 35;3 32 23 34 5 14;28 21 30 15 0 17;2 9 33 24 13 6;20 27 8 11 18 25;1 10 19 26 7 12];knights_tour(a)

ans =

  logical

   0
>> clear;a = [1 0 0;0 0 0;2 0 0];knights_tour(a)

ans =

  logical

   0
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值