搜索
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.util.*;
public class Main {
static int h;
static int w;
static char[][] board;
static boolean[][] visited;
static int ans = 1;
static int once = 0;
public static void main(String[] args) throws IOException {
h = rd.nextInt();
w = rd.nextInt();
board = new char[h][w];
for (int i = 0; i < h; i++) {
String str = rd.nextLine();
board[i] = str.toCharArray();
}
visited = new boolean[h][w];
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
if (board[i][j] == '.' && !visited[i][j] && canmove(i, j)) {
visited[i][j] = true;
int once = visit(i, j);
if (once > ans) {
ans = once;
}
}
}
}
System.out.println(ans);
}
static int[][] dir = new int[][]{
{0, 1}, {0, -1}, {1, 0}, {-1, 0}
};
public static boolean canmove(int row, int col) {
for (int i = 0; i < 4; i++) {
int x = row + dir[i][0];
int y = col + dir[i][1];
if (x >= 0 && x < h && y >= 0 && y < w && board[x][y] == '#') {
return false;
}
}
return true;
}
public static int visit(int row, int col) {
ArrayDeque<int[]> queue = new ArrayDeque<>();
queue.add(new int[]{row, col});
visited[row][col] = true;
int num = 0;
List<int[]> recover = new ArrayList<>();
while (!queue.isEmpty()) {
int[] node = queue.poll();
num++;
int x0 = node[0];
int y0 = node[1];
boolean canmove = true;
for (int i = 0; i < 4; i++) {
int x = x0 + dir[i][0];
int y = y0 + dir[i][1];
if (x >= 0 && x < h && y >= 0 && y < w && board[x][y] == '#') {
canmove = false;
break;
}
}
if (!canmove) {
recover.add(new int[]{x0, y0});
continue;
}
for (int i = 0; i < 4; i++) {
int x = x0 + dir[i][0];
int y = y0 + dir[i][1];
if (x >= 0 && x < h && y >= 0 && y < w && board[x][y] == '.' && !visited[x][y]) {
visited[x][y] = true;
queue.add(new int[]{x, y});
}
}
}
for (int[] r: recover) {
visited[r[0]][r[1]] = false;
}
return num;
}
}
class rd {
static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
static StringTokenizer tokenizer = new StringTokenizer("");
// nextLine()读取字符串
static String nextLine() throws IOException {
return reader.readLine();
}
// next()读取字符串
static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) tokenizer = new StringTokenizer(reader.readLine());
return tokenizer.nextToken();
}
// 读取一个int型数值
static int nextInt() throws IOException {
return Integer.parseInt(next());
}
// 读取一个double型数值
static double nextDouble() throws IOException {
return Double.parseDouble(next());
}
// 读取一个long型数值
static long nextLong() throws IOException {
return Long.parseLong(next());
}
// 读取一个BigInteger
static BigInteger nextBigInteger() throws IOException {
BigInteger d = new BigInteger(rd.nextLine());
return d;
}
}
标签:IOException,abc,return,int,Magnet,static,&&,new,Grid
From: https://www.cnblogs.com/fishcanfly/p/18162625