import times, strutils, sequtils, math, algorithm, tables, sets, lists, intsets import critbits, future, strformat, deques,heapqueue template `max=`(x,y) = x = max(x,y) template `min=`(x,y) = x = min(x,y) template `mod=`(x,y) = x = x mod y template scan2 = (scan(), scan()) template scan3 = (scan(), scan()) let read* = iterator: string {.closure.} = while true: (for s in stdin.readLine.split: yield s) proc scan(): int = read().parseInt proc scanf(): float = read().parseFloat proc toInt(c:char): int = return int(c) - int('0') const maxn = 500 var board:array[maxn,array[maxn,int]] costS:array[maxn,array[maxn,int]] costG:array[maxn,array[maxn,int]] fromS:array[maxn,array[maxn,(int,int)]] fromG:array[maxn,array[maxn,(int,int)]] proc onCompile()= for i in 0..0: var (c,h,w)=q.pop() #if touch[h][w]==false: ##touch[h][w] = true #fix-=1 #if fix==0: #break if c > costS[h][w]:continue if h-1>=0: if costS[h-1][w] > costS[h][w]+board[h-1][w]+1: costS[h-1][w] = costS[h][w]+board[h-1][w]+1 q.push((costS[h-1][w],h-1,w)) fromS[h-1][w] = ((h,w)) if h+1 costS[h][w]+board[h+1][w]+1: costS[h+1][w] = costS[h][w]+board[h+1][w]+1 q.push((costS[h+1][w],h+1,w)) fromS[h+1][w] = ((h,w)) if w-1>=0: if costS[h][w-1] > costS[h][w]+board[h][w-1]+1: costS[h][w-1] = costS[h][w]+board[h][w-1]+1 q.push((costS[h][w-1],h,w-1)) fromS[h][w-1] = ((h,w)) if w+1 costS[h][w]+board[h][w+1]+1: costS[h][w+1] = costS[h][w]+board[h][w+1]+1 q.push((costS[h][w+1],h,w+1)) fromS[h][w+1] = ((h,w)) q.clear() q.push((0,n-1,n-1)) #fix = n^2 #touch = newseqwith(n,newseqwith(n,false)) #echo "往路" while q.len>0: var (c,h,w)=q.pop() if c > costG[h][w]:continue #if touch[h][w]==false: #touch[h][w] = true #fix-=1 #if fix==0: #break if h-1>=0: if costG[h-1][w] > costG[h][w]+board[h-1][w]+1: costG[h-1][w] = costG[h][w]+board[h-1][w]+1 q.push((costG[h-1][w],h-1,w)) fromG[h-1][w] = ((h,w)) if h+1 costG[h][w]+board[h+1][w]+1: costG[h+1][w] = costG[h][w]+board[h+1][w]+1 q.push((costG[h+1][w],h+1,w)) fromG[h+1][w] = ((h,w)) if w-1>=0: if costG[h][w-1] > costG[h][w]+board[h][w-1]+1: costG[h][w-1] = costG[h][w]+board[h][w-1]+1 q.push((costG[h][w-1],h,w-1)) fromG[h][w-1] = ((h,w)) if w+1 costG[h][w]+board[h][w+1]+1: costG[h][w+1] = costG[h][w]+board[h][w+1]+1 q.push((costG[h][w+1],h,w+1)) fromG[h][w+1] = ((h,w)) #echo "復路" result = costS[n-1][n-1] for h in 0..0: var (fh,fw) = fromS[h][w] (th,tw) = fromG[h][w] result.min=2+costS[fh][fw]+costG[th][tw] echo solve()