浙大OJ 1002防火墙 DFS 暴力

🍑 ZOJ 1002 Fire Net
在这里插入图片描述

输出

4
.X..
....
XX..
....
2
XX
.X
3
.X.
X.X
.X.
3
...
.XX
.XX
4
....
....
....
....
0

输出

5
1
5
2
4

🍑 dfs

import java.io.*;
public class Main
{
	static int n, res;
	static char[][] a;
	static boolean[][] st;//记录此点有无被遍历过

	static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	//位移数组
	static int[] dx = { 1, 0, -1, 0 };
	static int[] dy = { 0, 1, 0, -1 };

	private static void dfs(int x, int y, int cnt)
	{
		if (!check(x, y))//坐标不合法直接返回
			return;
		res = Math.max(res, cnt);
		//直接暴力两重循环枚举每一个点
		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
			{
				a[x][y] = '#';// # 表示碉堡
				st[x][y] = true;//雁过留声
				dfs(i, j, cnt + 1);
                //回溯物归原主
				st[x][y] = false;
				a[x][y] = '.';
			}
	}
	private static boolean check(int x, int y)
	{
//      越界 或 已经走过 或 a[x][y] 是墙或碉堡 直接返回
		if (x >= n || x < 0 || y >= n || y < 0 || st[x][y] || a[x][y] == 'X' || a[x][y] == '#')
			return false;
		for (int i = 0; i < 4; i++)
		{
			for (int j = 1; j < n; j++)
			{
				int xx = x + j * dx[i];
				if (xx < 0 || xx >= n)
					break;
				if (a[xx][y] == '#')
					return false;
				if (a[xx][y] == 'X')
					break;
			}
			for (int j = 1; j < n; j++)
			{
				int yy = x + j * dy[i];
				if (yy < 0 || yy >= n)
					break;
				if (a[x][yy] == '#')
					return false;
				if (a[x][yy] == 'X')
					break;
			}
		}
		return true;
	}

	public static void main(String[] args) throws IOException
	{

		while (true)
		{
			n = Integer.parseInt(in.readLine());
			if (n == 0)
				break;
			a = new char[n][n];
			st = new boolean[n][n];
//             直接暴力枚举所有点
			for (int i = 0; i < n; i++)
				for (int j = 0; j < n; j++)
					st[i][j] = false;

			for (int i = 0; i < n; i++)
			{
				String s = in.readLine();
				for (int j = 0; j < n; j++)
					a[i][j] = s.charAt(j);
			}
			res = 0;
			for (int i = 0; i < n; i++)
				for (int j = 0; j < n; j++)
					dfs(i, j, 1);
			System.out.println(res);
		}
	}
}
posted @ 2023-04-21 23:52  兑生  阅读(57)  评论(0)    收藏  举报  来源
Live2D