First, you will need a function that gives you the valid neighbors for each cell, or node.
Then, for finding the shortest way to the goal, Breadth First Search should do. If you start from the start location and expand nodes until you hit the goal, you will always find the shortest path (if any). Alternatively, you can start from the goal and expand until you cover the entire map and you will have the shortest path to the goal for every starting location (this of course only makes sense if the goal is not moving).
For not getting stuck in loops, the most important aspect is to keep a list (or set, or map, or whatever) of the nodes that have already been expanded.
For more complex maps, or when different "costs" for certain paths come into play, you might rather use A* or Dijkstra's Algorithm.