← Home
```go
package main

import (
	"bufio"
	"fmt"
	"os"
)

func abs(a int) int {
	if a < 0 {
		return -a
	}
	return a
}

func main() {
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Split(bufio.ScanWords)
	buf := make([]byte, 0, 1024*1024)
	scanner.Buffer(buf, 1024*1024)

	nextInt := func() int {
		scanner.Scan()
		res := 0
		for _, b := range scanner.Bytes() {
			res = res*10 + int(b-'0')
		}
		return res
	}

	n := nextInt()
	m := nextInt()
	k := nextInt()

	grid := make([]int8, n*m)
	color_cells := make([][]int, k+1)

	for i := 0; i < n*m; i++ {
		c := int8(nextInt())
		grid[i] = c
		color_cells[c] = append(color_cells[c], i)
	}

	D := make([][]int32, k+1)
	Q := make([]int, n*m)

	for c := int8(1); c <= int8(k); c++ {
		D[c] = make([]int32, n*m)
		for i := 0; i < n*m; i++ {
			D[c][i] = -1
		}
		visited_color := make([]bool, k+1)
		head, tail := 0, 0

		for _, v := range color_cells[c] {
			D[c][v] = 0
			Q[tail] = v
			tail++
		}
		visited_color[c] = true

		for head < tail {
			u := Q[head]
			head++
			d := D[c][u]

			u_col := grid[u]
			if !visited_color[u_col] {
				visited_color[u_col] = true
				for _, v := range color_cells[u_col] {
					if D[c][v] == -1 {
						D[c][v] = d + 1
						Q[tail] = v
						tail++
					}
				}
			}

			r, c_idx := u/m, u%m

			if r > 0 {
				v := u - m
				if D[c][v] == -1 {
					D[c][v] = d + 1
					Q[tail] = v
					tail++
				}
			}
			if r < n-1 {
				v := u + m
				if D[c][v] == -1 {
					D[c][v] = d + 1
					Q[tail] = v
					tail++
				}
			}
			if c_idx > 0 {
				v := u - 1
				if D[c][v] == -1 {
					D[c][v] = d + 1
					Q[tail] = v
					tail++
				}
			}
			if c_idx < m-1 {
				v := u + 1
				if D[c][v] == -1 {
					D[c][v] = d + 1
					Q[tail] = v
					tail++
				}
			}
		}
	}

	q := nextInt()
	writer := bufio.NewWriter(os.Stdout)
	defer writer.Flush()

	for i := 0; i < q; i++ {
		r1 := nextInt() - 1
		c1 := nextInt() - 1
		r2 := nextInt() - 1
		c2 := nextInt() - 1

		u := r1*m + c1
		v := r2*m + c2
		ans := int32(abs(r1-r2) + abs(c1-c2))

		for c := int8(1); c <= int8(k); c++ {
			cost := D[c][u] + D[c][v] + 1
			if cost < ans {
				ans = cost
			}
		}
		fmt.Fprintln(writer, ans)
	}
}
```