-
Notifications
You must be signed in to change notification settings - Fork 0
/
eight_puzzle_problem.m
73 lines (59 loc) · 1.79 KB
/
eight_puzzle_problem.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
clc;
clear;
close all;
% A = [1 3 6; 5 0 8; 4 2 7];
% B = [1 2 3; 4 5 6; 7 8 0];
% A = [4 7 5; 2 0 6; 8 3 1];
% B = [1 4 7; 2 5 8; 3 6 0];
disp('Input example:')
disp('1 3 6')
disp('5 0 8')
disp('4 2 7')
try
fprintf('\nInput initial state row by row. Each element is separated by space or comma.\n')
str = convertCharsToStrings(input('','s'));
A = str2num(str{1});
str = convertCharsToStrings(input('','s'));
A = [A; str2num(str{1})];
str = convertCharsToStrings(input('','s'));
A = [A; str2num(str{1})];
if numel(unique(A)) ~= 9
disp('Initial state is incorrect')
error('Invalid input')
end
fprintf('\nInput goal state row by row. Each element is separated by space or comma.\n')
str = convertCharsToStrings(input('','s'));
B = str2num(str{1});
str = convertCharsToStrings(input('','s'));
B = [B; str2num(str{1})];
str = convertCharsToStrings(input('','s'));
B = [B; str2num(str{1})];
if numel(unique(B)) ~= 9
disp('Goal state is incorrect')
error('Invalid input')
end
if sum(A,'all') ~= sum(B,'all')
error('Invalid input')
end
fprintf('\nWrite 1 to use Manhattan distance or 2 to use Number of misplaced tiles.\n')
n = input('');
tic
switch n
case 1
[A,M,k] = puzzle_manh_dist(A,B);
case 2
[A,M,k] = puzzle_misplaced(A,B);
otherwise error('Invalid input')
end
fprintf('\n')
disp('Final result:')
disp(num2str(A(1,:)))
disp(num2str(A(2,:)))
disp(num2str(A(3,:)))
fprintf('\n')
toc
name = ['Number of iterations: ', num2str(k)];
disp(name)
catch
fprintf('\nInvalid input\n')
end