0 Replies - 1621 Views - Last Post: 06 March 2017 - 06:53 PM Rate Topic: -----

#1 jstanley6  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 39
  • Joined: 22-January 17

Regarding backtracking with a while loop

Posted 06 March 2017 - 06:53 PM

I am trying to solve a maze from a file. There is a start and a finish and I'm generating a loop to place numbers in the maze until it reaches the start in the Maze. However I can't get the part of the coding to backtrack through and replace the numbers with a "*" in the shortest path. On this particular maze the numbers stop at 17 so I used the number to declare a starting point, I know that will be wrong when i plug in the bigger mazes because they take more than 17 steps to complete. Here is what I got so far and the part that I can't get working is commented out. Thanks in advance!

maze = []

maze_file =File.open("maze1.mz")
while !maze_file.eof?
  maze << maze_file.gets.chomp.split('')
end
maze_file.close
row = 0
while row < maze.count
  col = 0
  while col < maze[row].count
    if maze[row][col] == 'F'
      f_row = row
      f_col = col
    end
    col += 1
  end
  row += 1
  puts
end
if maze[f_row-1][f_col] == ' '
  maze[f_row-1][f_col] = 0
end

if maze[f_row][f_col - 1] == ' '
  maze[f_row][f_col - 1] = 0
end

if maze[f_row + 1][f_col] == ' '
  maze[f_row + 1][f_col] = 0
end

if maze[f_row][f_col + 1] == ' '
  maze[f_row][f_col + 1] = 0
end
start = false
count = 1

while start == false
  count_row = 0
  maze.each { |value|
    count_col = 0
    value.each { |value|
      if value == count - 1
        if maze[count_row-1][count_col] == ' '
          maze[count_row-1][count_col] = count
        elsif maze[count_row-1][count_col] == 'S'
          start = true
        end
        if maze[count_row][count_col - 1] == ' '
          maze[count_row][count_col - 1] = count
        elsif maze[count_row][count_col - 1] == 'S'
          start = true
        end

        if maze[count_row + 1][count_col] == ' '
          maze[count_row + 1][count_col] = count
        elsif maze[count_row + 1][count_col] == 'S'
          start = true
        end

        if maze[count_row][count_col + 1] == ' '
          maze[count_row][count_col + 1] = count
        elsif maze[count_row][count_col + 1] == 'S'
          start = true
        end
      end
      count_col += 1
    }
    count_row += 1
  }
  count += 1
end

s_row = 16
s_col = 8
num = 17
while num > 0

  # if maze[s_row - 1][s_col] == num
  #   maze[s_row - 1][s_col] = '*'
  #
  # elsif maze[s_row][s_col + 1] == num
  #   maze[s_row][s_col + 1] = '*'
  #
  # elsif maze[s_row + 1][s_col] == num
  #   maze[s_row + 1][s_col] = '*'
  #
  # elsif (maze[s_row][s_col - 1]) == num
  #   maze[s_row][s_col - 1] = '*'
  #
  # end
  # num -= 1
end

maze.each do |row|
  row.each do |cell|
    print cell
  end
  puts
end



Is This A Good Question/Topic? 0
  • +

Page 1 of 1