dfs: 注意matlab里面的全局变量的使用
test.m:
clc; clear; global A ii dx dy vis minpath path A=... [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1; 1 2 0 0 1 1 0 0 0 0 1 1 1 1 1 1; 1 0 1 0 0 0 0 1 1 0 0 0 1 1 1 1; 1 0 1 1 1 1 0 0 1 1 0 0 0 0 1 1; 1 0 0 0 0 1 1 0 1 0 0 1 1 1 1 1; 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1; 1 0 0 0 0 1 1 1 1 1 1 0 1 1 1 1; 1 0 1 0 0 1 1 0 0 0 0 0 1 1 1 1; 1 0 1 0 1 1 1 0 1 0 0 1 1 1 1 1; 1 0 1 0 0 0 0 0 1 1 0 0 0 0 1 1; 1 0 1 1 0 1 1 0 0 0 1 1 1 0 1 1; 1 0 0 1 0 1 1 0 1 0 0 0 0 0 1 1; 1 1 1 1 0 1 1 0 1 1 1 1 0 0 1 1; 1 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1; 1 1 1 1 1 1 1 1 1 1 0 0 0 0 3 1; 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1; ]; minpath = inf dx = [1, -1, 0, 0]; dy = [0, 0, -1, 1]; vis = zeros(16,16); disp('迷宫图') % A % A = num2str(A)%% 2为入口点(2,2), 3为出口为A(15,15) ii = 0; [xx, yy] = size(A); visits(2,2); disp('第一种走出迷宫图') fprintf('最短路:%d', minpath); path ys = max(path, A) % A = num2str(A)
visits.m:
function [i,j]=visits(i,j) global A ii dx dy vis minpath path if A(i,j) == 3 % A(i,j) = 3; if ii < minpath minpath = ii; path = vis; end fprintf('found: %d ', ii); % A = num2str(A) % vis = num2str(vis) return ; end % if ii > 200 % return % end for xi = 1:4 x = i + dx(xi); y = j + dy(xi); if x >= 1 && x <= 16 && y >= 1 && y <= 16 && A(x,y) ~= 1 && vis(x,y) == 0 vis(x,y) = 8; ii = ii + 1; % t = A(x,y); % A(x,y) = 8; visits(x, y); % A(x,y) = t; ii = ii - 1; vis(x,y) = 0; end end end