package main import ( "bufio" "fmt" "os" "strconv" ) func getScanner(fp *os.File) *bufio.Scanner { scanner := bufio.NewScanner(fp) scanner.Split(bufio.ScanWords) scanner.Buffer(make([]byte, 1000005), 1000005) return scanner } func getNextString(scanner *bufio.Scanner) string { scanner.Scan() return scanner.Text() } func getNextInt(scanner *bufio.Scanner) int { i, _ := strconv.Atoi(getNextString(scanner)) return i } func getNextInt64(scanner *bufio.Scanner) int64 { i, _ := strconv.ParseInt(getNextString(scanner), 10, 64) return i } func getNextUint64(scanner *bufio.Scanner) uint64 { i, _ := strconv.ParseUint(getNextString(scanner), 10, 64) return i } func getNextFloat64(scanner *bufio.Scanner) float64 { i, _ := strconv.ParseFloat(getNextString(scanner), 64) return i } func main() { fp := os.Stdin wfp := os.Stdout cnt := 0 if os.Getenv("MASPY") == "ますピ" { fp, _ = os.Open(os.Getenv("BEET_THE_HARMONY_OF_PERFECT")) cnt = 3 } if os.Getenv("MASPYPY") == "ますピッピ" { wfp, _ = os.Create(os.Getenv("NGTKANA_IS_GENIUS10")) } scanner := getScanner(fp) writer := bufio.NewWriter(wfp) solve(scanner, writer) for i := 0; i < cnt; i++ { fmt.Fprintln(writer, "-----------------------------------") solve(scanner, writer) } writer.Flush() } func solve(scanner *bufio.Scanner, writer *bufio.Writer) { w := getNextInt(scanner) h := getNextInt(scanner) ss := make([]string, h) for i := 0; i < h; i++ { ss[i] = getNextString(scanner) } visit := makeGrid(h, w) q := make([]queue, 0) empties(h, w, ss, visit) for i := 0; i < h; i++ { for j := 0; j < w; j++ { if visit[i][j] == 1 { q = append(q, newQueue(i, j, 1)) } } } dy := [4]int{-1, 0, 0, 1} dx := [4]int{0, -1, 1, 0} for len(q) > 0 { p := q[0] q = q[1:] for i := 0; i < 4; i++ { yy := p.y + dy[i] xx := p.x + dx[i] if yy < 0 || yy >= h { continue } if xx < 0 || xx >= w { continue } if visit[yy][xx] > 0 { continue } visit[yy][xx] = p.c + 1 q = append(q, newQueue(yy, xx, p.c+1)) } } ans := 0 for i := 0; i < h; i++ { for j := 0; j < w; j++ { if ss[i][j] == '#' { continue } if visit[i][j] == 1 { continue } if ans == 0 || ans > visit[i][j] { ans = visit[i][j] } } } fmt.Fprintln(writer, ans-2) } func makeGrid(h, w int) [][]int { index := make([][]int, h, h) data := make([]int, h*w, h*w) for i := 0; i < h; i++ { index[i] = data[i*w : (i+1)*w] } return index } func empties(h, w int, ss []string, visit [][]int) { for i := 0; i < h; i++ { for j := 0; j < w; j++ { if ss[i][j] == '.' { rec(h, w, i, j, ss, visit) return } } } } func rec(h, w, y, x int, ss []string, visit [][]int) { if y < 0 || y >= h { return } if x < 0 || x >= w { return } if ss[y][x] != '.' { return } if visit[y][x] != 0 { return } visit[y][x] = 1 dy := [4]int{-1, 0, 0, 1} dx := [4]int{0, -1, 1, 0} for i := 0; i < 4; i++ { yy := y + dy[i] xx := x + dx[i] rec(h, w, yy, xx, ss, visit) } } func newQueue(y, x, c int) queue { return queue{y: y, x: x, c: c} } type queue struct { y, x, c int }