这题使用深度优先搜索
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
int res = 0;
public static void main(String[] args){
// TODO Auto-generated method stub
Main ma = new Main();
ma.solve();
}
private void solve() {
int map[][] = new int[4][4];
int n = 0;
// TODO Auto-generated method stub
File f = new File("in");
try {
BufferedReader cin = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader cin = new BufferedReader(new InputStreamReader(System.in));
while(true){
res = 0;
try {
n = Integer.parseInt(cin.readLine());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(n==0)break;
String tmpLine = null;
for(int i=0;i<n;i++){
try {
tmpLine = cin.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int j=0;j<n;j++){
if(tmpLine.charAt(j)=='.')
map[i][j] = 0;
else
map[i][j] = 1;
}
}
dfs(0, 0, n, map, 0);
System.out.println(res);
}
}
private void dfs(int a, int b, int n, int[][] map, int result) {
// TODO Auto-generated method stub
if(result>res)res = result;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++){
if(map[i][j]==0){
map[i][j] = 2;
if(ok(n, map)){
//print(n, map);
dfs(i, j, n, map, result+1);
}
map[i][j] = 0;
}
}
}
private void print(int n, int[][] map) {
// TODO Auto-generated method stub
for(int i=0;i<n;i++){
for(int j=0;j<n;j++)
System.out.print(map[i][j]);
System.out.println();
}
System.out.println();
}
private boolean ok(int n, int[][] map) {
// TODO Auto-generated method stub
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
if(map[i][j]==2){
int a = i;
while((++a)<n){
if(map[a][j]==2)
return false;
if(map[a][j]==1)
break;
}
a = i;
while((a--)>0){
if(map[a][j]==2)
return false;
if(map[a][j]==1)
break;
}
int b = j;
while((++b)<n){
if(map[i][b]==2)
return false;
if(map[i][b]==1)
break;
}
b = j;
while((b--)>0){
if(map[i][b]==2)
return false;
if(map[i][b]==1)
break;
}
}
}
}
return true;
}
}