- import java.io.BufferedInputStream;
- import java.util.Scanner;
- public class Main {
- static char pos[][] = new char[4][4];
- static int numOfLegalPos = 0;
- static int maxNumOfLegalPos = 0;
- static int n;
- public static boolean check(int y, int x) {
- for (int i = x + 1; i < n; i++) {// check right dir
- if (pos[y][i] == 'X') {
- break;
- } else if (pos[y][i] == '0') {// if there is a wall in the same line,return false means there cant put a city
- return false;
- }
- }
- for (int i = x - 1; i >= 0; i--) {// check left dir
- if (pos[y][i] == 'X') {
- break;
- } else if (pos[y][i] == '0') {
- return false;
- }
- }
- for (int i = y + 1; i < n; i++) {// check down dir
- if (pos[i][x] == 'X') {
- break;
- } else if (pos[i][x] == '0') {
- return false;
- }
- }
- for (int i = y - 1; i >= 0; i--) {// check up dir
- if (pos[i][x] == 'X') {
- break;
- } else if (pos[i][x] == '0') {
- return false;
- }
- }
- return true;
- }
- public static void dfs(int n) {
- if (numOfLegalPos > maxNumOfLegalPos) {
- maxNumOfLegalPos = numOfLegalPos;
- }
- for (int y = 0; y < n; y++) {
- for (int x = 0; x < n; x++) {
- if (pos[y][x] == 'X' || pos[y][x] == '0') {// if here is a wall or a city ingore it.
- continue;
- } else if (check(y, x)) {// if here can put a city
- pos[y][x] = '0';
- numOfLegalPos++;
- dfs(n);
- pos[y][x] = '.';
- numOfLegalPos--;
- }
- }
- }
- }
- public static void main(String[] args) {
- Scanner sc = new Scanner(new BufferedInputStream(System.in));
- n = sc.nextInt();// line of maze
- while (n != 0) {
- for (int i = 0; i < n; i++) {// transform strings into chars
- String tmp = sc.next();
- for (int j = 0; j < n; j++) {
- pos[i][j] = tmp.charAt(j);
- }
- }
- dfs(n);
- System.out.println(maxNumOfLegalPos);
- n = sc.nextInt();
- maxNumOfLegalPos=0;
- }
- }
- }
明明只是个初级题目,居然让自己忙了这么久。看来不扎实啊。。。
一开始的想法是:先将某个点设为blockhouse,然后按行检索其他所有位置是否可以放下blockhouse,但是用简单循环一直是WA。其中的错误在于。。如果用简单循环把第后面的位置设为blackhouse后,就忽略了前面位置已经设为blackhouse的状态。因此用dfs检索所有可能项,简单循环就会丢失一部分。