|
| 1 | +```java |
| 2 | +import java.util.*; |
| 3 | +import java.io.*; |
| 4 | + |
| 5 | +public class boj23352 { |
| 6 | + static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 7 | + static StringTokenizer st; |
| 8 | + static void nextLine() throws Exception {st = new StringTokenizer(br.readLine());} |
| 9 | + static int nextInt() {return Integer.parseInt(st.nextToken());} |
| 10 | + |
| 11 | + static int N, M, answer, dep; |
| 12 | + static int[][] map; |
| 13 | + static int[][] dir = {{1,0}, {0,1}, {0,-1}, {-1,0}}; |
| 14 | + public static void main(String[] args) throws Exception { |
| 15 | + nextLine(); |
| 16 | + N = nextInt(); |
| 17 | + M = nextInt(); |
| 18 | + map = new int[N][M]; |
| 19 | + answer = 0; |
| 20 | + dep = 0; |
| 21 | + for (int i = 0; i < N; i++) { |
| 22 | + nextLine(); |
| 23 | + for (int j = 0; j < M; j++) map[i][j] = nextInt(); |
| 24 | + } |
| 25 | + for (int i = 0; i < N; i++) { |
| 26 | + for (int j = 0; j < M; j++) { |
| 27 | + if (map[i][j] == 0) continue; |
| 28 | + bfs(i, j); |
| 29 | + } |
| 30 | + } |
| 31 | + System.out.println(answer); |
| 32 | + } |
| 33 | + |
| 34 | + static void bfs(int y, int x) { |
| 35 | + boolean[][] visited = new boolean[N][M]; |
| 36 | + Queue<Pos> q = new LinkedList<>(); |
| 37 | + q.add(new Pos(y, x, 0)); |
| 38 | + visited[y][x] = true; |
| 39 | + |
| 40 | + while (!q.isEmpty()) { |
| 41 | + Pos curr = q.poll(); |
| 42 | + boolean flag = true; |
| 43 | + |
| 44 | + for (int[] d : dir) { |
| 45 | + int ny = curr.y + d[0]; |
| 46 | + int nx = curr.x + d[1]; |
| 47 | + if (ny < 0 || ny >= N || nx < 0 || nx >= M || visited[ny][nx] || map[ny][nx] == 0) continue; |
| 48 | + visited[ny][nx] = true; |
| 49 | + flag = false; |
| 50 | + q.add(new Pos(ny, nx, curr.cnt+1)); |
| 51 | + } |
| 52 | + if (flag) { |
| 53 | + if (dep < curr.cnt) { |
| 54 | + dep = curr.cnt; |
| 55 | + answer = map[y][x] + map[curr.y][curr.x]; |
| 56 | + } else if (dep == curr.cnt) { |
| 57 | + answer = Math.max(answer, map[y][x] + map[curr.y][curr.x]); |
| 58 | + } |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +class Pos { |
| 65 | + int y, x, cnt; |
| 66 | + public Pos(int y, int x, int cnt) { |
| 67 | + this.y = y; |
| 68 | + this.x = x; |
| 69 | + this.cnt = cnt; |
| 70 | + } |
| 71 | +} |
| 72 | +``` |
0 commit comments