import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.regex.Pattern;
/*
プログラミングのお題スレ Part13
//mevius.5ch.net/test/read.cgi/tech/1549160513/316
316 名前:デフォルトの名無しさん[sage] 投稿日:2019/02/22(金) 21:42:16.23 ID:THqrb0iU
お題:
長方形のフィールドが与えられる。フィールド上では上下左右に移動することができる。
各マスの数字はそのマスに入るためのコストを表す。
SからGに向かうときの最小コストを求めよ。(SとGのコストは0とする)
S5111
1115G
=> 6
S1111
98642
G1111
=> 9
13457689768914512071934123457
G4578901258901212890361125312
37890423076834712378998725463
16890102569615902061456259893
34582934765923812893461515232
57896123896741378915691551697
89013897456123457162501835479
21389046013845610034623405686
8902346203948612341356362342S
=> ?
*/
class Ideone
{
public static void main
(String[] args
) {
try (Scanner in
= new Scanner
(System.
in)) {
while (in.hasNextLine())
{
ArrayList<String> data = new ArrayList<>();
while (in.hasNextLine())
{
if (line.isEmpty()) break;
data.add(line);
}
solve(data);
}
}
}
static Pattern FIELD_PATTERN = Pattern.compile("[0-9SG]+");
static void solve(List<String> data)
{
Point start
= null, goal
= null; int width = data.get(0).length();
int height = data.size();
int[][] cost = new int[height][width];
for (int y = 0; y < height; y++)
{
if (width != s.length())
if (!FIELD_PATTERN.matcher(s).matches())
for (int x = 0; x < s.length(); x++)
{
char c = s.charAt(x);
if (c == 'S')
{
if (start
== null) start
= new Point(x, y
); } else if (c == 'G')
{
if (goal
== null) goal
= new Point(x, y
); } else
{
cost[y][x] = c - '0';
}
}
}
int[][] score = new int[height][width];
boolean[][] flag = new boolean[height][width];
for (int[] is : score)
score[start.y][start.x] = 0;
while (true)
{
Point next
= min
(score, flag
); if (next == null) break;
flag[next.y][next.x] = true;
if (next.x > 0)
{
int s = score[next.y][next.x] + cost[next.y][next.x - 1];
if (s < score[next.y][next.x - 1]) score[next.y][next.x - 1] = s;
}
if (next.x < width - 1)
{
int s = score[next.y][next.x] + cost[next.y][next.x + 1];
if (s < score[next.y][next.x + 1]) score[next.y][next.x + 1] = s;
}
if (next.y > 0)
{
int s = score[next.y][next.x] + cost[next.y - 1][next.x];
if (s < score[next.y - 1][next.x]) score[next.y - 1][next.x] = s;
}
if (next.y < height - 1)
{
int s = score[next.y][next.x] + cost[next.y + 1][next.x];
if (s < score[next.y + 1][next.x]) score[next.y + 1][next.x] = s;
}
}
System.
out.
println("=>" + score
[goal.
y][goal.
x]); }
// キュー作るの面倒だったので全箇所から最小スコア部分を調べるw
static Point min
(int[][] score,
boolean[][] flag
) {
int h = score.length;
int w = score[0].length;
for (int y = 0; y < h; y++)
{
for (int x = 0; x < w; x++)
{
if (flag[y][x]) continue;
if (min > score[y][x])
{
min = score[y][x];
}
}
}
return point;
}
}