Guest User

Dag 15 in MATLAB

a guest
Dec 15th, 2021
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 2.04 KB | None | 0 0
  1. fid=fopen('input.txt');
  2. x=[];
  3. while 1
  4.     tline = fgetl(fid);
  5.     if ~ischar(tline), break, end
  6.     x = [x;double(tline)-48];
  7. end
  8. fclose(fid);
  9.  
  10. x1 = x+1;  x1(x1>9)=1;
  11. x2 = x1+1; x2(x2>9)=1;
  12. x3 = x2+1; x3(x3>9)=1;
  13. x4 = x3+1; x4(x4>9)=1;
  14. x5 = x4+1; x5(x5>9)=1;
  15. x6 = x5+1; x6(x6>9)=1;
  16. x7 = x6+1; x7(x7>9)=1;
  17. x8 = x7+1; x8(x8>9)=1;
  18.  
  19. x = [x,x1,x2,x3,x4;
  20.      x1,x2,x3,x4,x5;
  21.      x2,x3,x4,x5,x6;
  22.      x3,x4,x5,x6,x7;
  23.      x4,x5,x6,x7,x8];
  24.  
  25. L                   = size(x,1);
  26. startIdx            = 1;
  27. goalIdx             = L*L;
  28. openSet             = startIdx;
  29. cameFrom            = [];
  30. gScore              = inf(L);
  31. gScore(startIdx)    = 0;
  32. fScore              = inf(L);
  33. fScore(startIdx)    = (L-1)+(L-1); % Manhattan distance from start to finish
  34.  
  35. while ~isempty(openSet)
  36.    
  37.     [~,idx]     = min(fScore(openSet));
  38.     current     = openSet(idx);
  39.    
  40.     if current==goalIdx
  41.         disp('path complete')
  42.         break
  43.     end
  44.    
  45.     openSet(openSet == current) = [];
  46.    
  47.     [r,c]   = ind2sub(size(x),current);
  48.     r1 = r-1; c1 = c;
  49.     r2 = r+1; c2 = c;
  50.     r3 = r; c3 = c-1;
  51.     r4 = r; c4 = c+1;
  52.    
  53.     neighbours = [];
  54.     if r1>0
  55.         neighbours = [neighbours,sub2ind(size(x),r1,c1)];
  56.     end
  57.     if r2<(L+1)
  58.         neighbours = [neighbours,sub2ind(size(x),r2,c2)];
  59.     end
  60.     if c3>0
  61.         neighbours = [neighbours,sub2ind(size(x),r3,c3)];
  62.     end
  63.     if c4<(L+1)
  64.         neighbours = [neighbours,sub2ind(size(x),r4,c4)];
  65.     end
  66.    
  67.     for i=1:size(neighbours,2)
  68.         tentative_gScore = gScore(current) + x(neighbours(i));
  69.         if tentative_gScore < gScore(neighbours(i))
  70.             [rn,cn]          = ind2sub(size(x),neighbours(i));
  71.             cameFrom(rn,cn)  = current;
  72.             gScore(rn,cn)    = tentative_gScore;
  73.             h                = (L-rn)+(L-cn);
  74.             fScore(rn,cn)    = tentative_gScore + h;
  75.            
  76.             if ~any(neighbours(i)==openSet)
  77.                 openSet = [openSet,neighbours(i)];
  78.             end
  79.         end
  80.     end
  81. end
  82. disp(fScore(end));
Advertisement
Add Comment
Please, Sign In to add comment