extern crate core;

use std::fmt;
use std::cmp::{Ordering, min, max};
use std::fmt::{Display, Error, Formatter, Binary};
use std::f32::MAX;
use std::ops::{Add, Sub, Mul, Div, Neg, Index, IndexMut};
use std::collections::{BTreeMap, VecDeque, BinaryHeap, BTreeSet};

fn show<T: Display>(vec: &Vec<T>) {
    if vec.is_empty() {
        println!("[]");
    }else {
        print!("[{}", vec[0]);
        for i in 1 .. vec.len() {
            print!(", {}", vec[i]);
        }
        println!("]");
    }
}
fn show2<T: Display>(vec: &Vec<Vec<T>>) {
    if vec.is_empty() {
        println!("[]");
    }else {
        for l in vec {
            show(l);
        }
    }
}
macro_rules! read_line{
    () => {{
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).ok();
        line
    }};
    (delimiter: ' ') => {
        read_line!().split_whitespace().map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (delimiter: $p:expr) => {
        read_line!().split($p).map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (' ') => {
        read_line!(delimiter: ' ')
    };
    ($delimiter:expr) => {
        read_line!(delimiter: $delimiter)
    };
    (' '; $ty:ty) => {
        read_line!().split_whitespace().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
    ($delimiter:expr; $ty:ty) => {
        read_line!($delimiter).into_iter().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
}
macro_rules! read_value{
    () => {
        read_line!().trim().parse().ok().unwrap()
    }
}
macro_rules! let_all {
    ($($n:ident:$t:ty),*) => {
        let line = read_line!(delimiter: ' ');
        let mut iter = line.iter();
        $(let $n:$t = iter.next().unwrap().parse().ok().unwrap();)*
    };
}
macro_rules! let_mut_all {
    ($($n:ident:$t:ty),*) => {
        let line = read_line!(delimiter: ' ');
        let mut iter = line.iter();
        $(let mut $n:$t = iter.next().unwrap().parse().ok().unwrap();)*
    };
}
#[derive(Copy, Clone)]
struct Point {
    x: i32, y: i32
}
impl Point {
    fn new(x: usize, y: usize) -> Point {
        Point{x: x as i32, y: y as i32}
    }
    fn manhattan_distance(&self, other: &Self) -> i32 {
        abs(self.x - other.x) + abs(self.y - other.y)
    }
}
fn abs(value: i32) -> i32 {
    if value > 0 {
        value
    }else {
        -value
    }
}
fn main() {
    loop {
        let_all!(w: usize, h: usize);
        if w == 0 && h == 0 {
            return
        }
        let mut state: Vec<Vec<String>> = Vec::with_capacity(h);
        for _ in 0 .. h {
            state.push(read_line!(' '));
        }
        let mut points = vec![Vec::new(); 1];
        for x in 0 .. w {
            for y in 0 .. h {
                match &state[y][x][..] {
                    "S" => points[0].push(Point::new(x, y)),
                    _ => {}
                }
            }
        }
        let mut current = 1;
        while !points.last().unwrap().is_empty() {
            points.push(Vec::new());
            for x in 0 .. w {
                for y in 0 .. h {
                    match state[y][x].parse::<i32>() {
                        Ok(c) if c == current => points.last_mut().unwrap().push(Point::new(x, y)),
                        _ => {}
                    }
                }
            }
            current += 1;
        }
        for x in 0 .. w {
            for y in 0 .. h {
                match &state[y][x][..] {
                    "G" => points.last_mut().unwrap().push(Point::new(x, y)),
                    _ => {}
                }
            }
        }
        let mut min_steps = vec![0; 1];
        let mut current = &points[0];
        for i in 1 .. points.len() {
            let next = &points[i];
            let mut next_min_step = vec![std::i32::MAX; next.len()];
            for fi in 0 .. current.len() {
                for ti in 0 .. next.len(){
                    if next_min_step[ti] > min_steps[fi] + current[fi].manhattan_distance(&next[ti]) {
                        next_min_step[ti] = min_steps[fi] + current[fi].manhattan_distance(&next[ti]);
                    }
                }
            }
            current = next;
            min_steps = next_min_step;
        }
        println!("{}", min_steps[0]);
    }
}


Measured memory_bytes: 5060