Magnet

package IM; import java.io.File; import java.io.FileNotFoundException; import java.util.Scanner; public class Magnet { static int T, N, M, D, x, y, Ans; static int[][] map; static int[] arrDraw; static final int UP = 1, RIGHT = 2, DOWN = 3, LEFT = 4; public static int magnet(int i, int j, int rotate) { int moves = 0; while (true) { if (rotate == UP) { i--; } else if (rotate == DOWN) { i++; } else if (rotate == RIGHT) { j++; } else if (rotate == LEFT) { j--; } if (i >= 0 && i < N && j >= 0 && j < M && map[i][j] == 0) { x = i; y = j; moves++; } else break; } return moves; } public static void main(String[] args) throws FileNotFoundException { Scanner sc = new Scanner(new File("input_magnet.txt")); T = sc.nextInt(); for (int tc = 1; tc <= T; tc++) { N = sc.nextInt(); M = sc.nextInt(); D = sc.nextInt(); map = new int[N][M]; arrDraw = new int[D]; Ans = 0; // Doc data vao mang Draw for (int i = 0; i < D; i++) { arrDraw[i] = sc.nextInt(); } // Doc data vao mang MN for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { map[i][j] = sc.nextInt(); //System.out.print(map[i][j] + " "); if (map[i][j] == 2) { x = i; y = j; } } //System.out.println(); } // Xu ly for (int d = 0; d < D; d++) { Ans += magnet(x, y, arrDraw[d]); } // In ket qua System.out.println("Case#" + tc + " " + Ans); } } }
50
4 5 6
3 4 2 3 2 1
2 0 0 0 0
0 1 0 0 1
0 1 0 0 1
0 0 0 0 0
6 7 8
4 1 4 2 1 2 4 3
0 0 0 0 0 0 0
0 0 0 0 1 0 0
0 0 0 2 0 0 1
1 0 0 0 0 0 1
0 1 0 0 1 0 0
0 0 0 0 0 0 0
8 9 6
1 2 4 3 2 4
0 0 0 1 0 0 0 0 0
0 0 1 0 0 0 0 0 2
0 0 1 0 0 0 0 0 0
1 0 0 0 1 0 0 0 0
1 0 0 0 0 0 1 0 0
0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0
0 0 0 1 1 0 0 0 0
9 10 8
1 2 1 4 1 4 2 1
0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 0 0 1 0
0 0 0 0 1 0 0 0 0 0
0 0 0 0 0 0 1 0 0 1
0 0 0 0 0 0 0 0 0 0
0 1 0 1 0 0 0 0 1 0
0 0 1 0 0 0 0 0 0 1
0 2 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0
==================
Case#1 7
Case#2 19
Case#3 16
Case#4 11
Case#5 45
Case#6 49
Case#7 28
Case#8 32
Case#9 47
Case#10 135
Case#11 143
Case#12 133
Case#13 179
Case#14 89
Case#15 135
Case#16 145
Case#17 211
Case#18 182
Case#19 161
Case#20 171
Case#21 214
Case#22 103
Case#23 83

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.