|
| 1 | +```import java.io.*; |
| 2 | +import java.util.*; |
| 3 | +
|
| 4 | +public class Main { |
| 5 | + private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 6 | + private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); |
| 7 | + private static List<int[]>[] d; |
| 8 | + private static int[][] map; |
| 9 | + private static boolean[][] visited; |
| 10 | + private static int N, M; |
| 11 | + public static void main(String[] args) throws IOException { |
| 12 | + init(); |
| 13 | +
|
| 14 | + bw.write(BFS(1, 1) + "\n"); |
| 15 | + bw.flush(); |
| 16 | + bw.close(); |
| 17 | + br.close(); |
| 18 | + } |
| 19 | +
|
| 20 | + private static void init() throws IOException { |
| 21 | + N = Integer.parseInt(br.readLine()); |
| 22 | + M = Integer.parseInt(br.readLine()); |
| 23 | +
|
| 24 | + map = new int[N+1][M+1]; |
| 25 | + visited = new boolean[N+1][M+1]; |
| 26 | + d = new List[1000001]; |
| 27 | +
|
| 28 | + for (int i = 0; i < 1000001; i++) { |
| 29 | + d[i] = new ArrayList<>(); |
| 30 | + } |
| 31 | +
|
| 32 | + for (int i = 1; i <= N; i++) { |
| 33 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 34 | + for (int j = 1; j <= M; j++) { |
| 35 | + map[i][j] = Integer.parseInt(st.nextToken()); |
| 36 | + } |
| 37 | + } |
| 38 | + } |
| 39 | +
|
| 40 | + private static String BFS(int x, int y) { |
| 41 | + Queue<int[]> q = new ArrayDeque<>(); |
| 42 | + visited[x][y] = true; |
| 43 | + q.add(new int[] {x, y}); |
| 44 | +
|
| 45 | + while (!q.isEmpty()) { |
| 46 | + int[] current = q.poll(); |
| 47 | + if (current[0] == N && current[1] == M) { |
| 48 | + return "yes"; |
| 49 | + } |
| 50 | +
|
| 51 | + if (d[map[current[0]][current[1]]].size() == 0) { |
| 52 | + findFactor(map[current[0]][current[1]]); |
| 53 | + } |
| 54 | +
|
| 55 | + for (int[] element : d[map[current[0]][current[1]]]) { |
| 56 | + for (int i = 0; i < element.length; i++) { |
| 57 | + int nx = element[i]; |
| 58 | + int ny = element[i^1]; |
| 59 | +
|
| 60 | + if (OOB(nx, ny) || visited[nx][ny]) continue; |
| 61 | + visited[nx][ny] = true; |
| 62 | + q.add(new int[] {nx, ny}); |
| 63 | + } |
| 64 | + } |
| 65 | + } |
| 66 | +
|
| 67 | + return "no"; |
| 68 | + } |
| 69 | +
|
| 70 | + private static void findFactor(int n) { |
| 71 | + for (int i = 1; i <= Math.sqrt(n); i++) { |
| 72 | + if (n % i == 0) { |
| 73 | + d[n].add(new int[] {i, n / i}); |
| 74 | + } |
| 75 | + } |
| 76 | + } |
| 77 | +
|
| 78 | + private static boolean OOB(int nx, int ny) { |
| 79 | + return nx < 1 || nx > N || ny < 1 || ny > M; |
| 80 | + } |
| 81 | +} |
| 82 | +
|
| 83 | +``` |
0 commit comments