Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.Point;
- import java.io.*;
- import java.util.HashSet;
- import java.util.LinkedList;
- import java.util.Scanner;
- public class F {
- public static void main(String args[]) throws IOException {
- new F().doIt();
- }
- public void doIt() throws IOException {
- BufferedReader in = new BufferedReader(new FileReader("F.in"));
- PrintStream out = new PrintStream(new File("F.out"));
- String input = in.readLine();
- while(input != null && !input.equals("")) {
- int row, col;
- String[] parsed = input.split(" +");
- row = Integer.parseInt(parsed[0]);
- col = Integer.parseInt(parsed[1]);
- int[][][] effect = new int[10][row][col];
- HashSet<Point>[] lists = new HashSet[10];
- for (int x=0; x<10; x++)
- lists[x] = new HashSet<Point>();
- for (int x=0; x<row; x++) {
- input = in.readLine();
- for (int y=0; y<col; y++) {
- lists[input.charAt(y)-'0'].add(new Point(x, y));
- }
- }
- int[] dx = {0, 1, -1, 0};
- int[] dy = {1, 0, 0, -1};
- for (int type=0; type<10; type++) {
- LinkedList<Magic> queue = new LinkedList<Magic>();
- for (Point p : lists[type]) {
- queue.add(new Magic(p, 0, p));
- effect[type][p.x][p.y] = -1;
- }
- while(!queue.isEmpty()) {
- Magic cur = queue.poll();
- for (int d=0; d<4; d++) {
- if (cur.loc.x + dx[d] >= 0 && cur.loc.x + dx[d] < row &&
- cur.loc.y + dy[d] >= 0 && cur.loc.y + dy[d] < col) {
- int nextRow = cur.loc.x + dx[d];
- int nextCol = cur.loc.y + dy[d];
- if (effect[type][nextRow][nextCol] == 0) {
- effect[type][nextRow][nextCol] = cur.dist + 1;
- queue.add(new Magic(cur.src, cur.dist + 1, new Point(nextRow, nextCol)));
- }
- else if (effect[type][cur.src.x][cur.src.y] == -1) {
- if (lists[type].contains(new Point(nextRow, nextCol)))
- effect[type][cur.src.x][cur.src.y] = 1;
- else
- effect[type][cur.src.x][cur.src.y] = cur.dist + effect[type][nextRow][nextCol]+1;
- }
- }
- }
- }
- }
- int ans = 0;
- for (int x = 0; x < row; x++) {
- for (int y=0; y < col; y++) {
- for (int z=0; z<10; z++) {
- ans += effect[z][x][y] * 2;
- }
- System.out.print(effect[1][x][y]);
- }
- System.out.println();
- }
- out.println(ans);
- input = in.readLine();
- }
- }
- class Magic {
- public Point src;
- public int dist;
- public Point loc;
- public Magic(Point s, int d, Point l) {
- src = s;
- dist = d;
- loc = l;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement