Skip to content

Commit 29151bd

Browse files
committed
DFS栈溢出真他妈无语
1 parent 2748ff1 commit 29151bd

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

src/DFS/填充封闭区域.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package DFS;
2+
3+
/**
4+
* Created by 周杰伦 on 2018/3/31.
5+
*/
6+
public class 填充封闭区域 {
7+
public static void main(String[] args) {
8+
9+
}
10+
public void solve(char[][] board) {
11+
if (board == null || board.length == 0)return;
12+
int m = board.length;
13+
int n = board[0].length;
14+
if (m <= 2 || n <= 2)return;
15+
16+
int [][] visit = new int[m][n];
17+
for (int i = 1;i < m - 1;i ++) {
18+
for (int j = 1;j < n - 1;j ++) {
19+
if (board[i][j] == 'O' && legal(board, i, j)) {
20+
dfs(board,visit,i,j);
21+
}
22+
}
23+
}
24+
}
25+
public boolean dfs(char[][] board, int [][]visit, int x, int y) {
26+
if (x < 0 || y < 0 || x >= board.length || y >= board[0].length) return false;
27+
if (!legal(board, x, y)) return false;
28+
if (board[x][y] == 'X') return true;
29+
if (visit[x][y] == 1)return true;
30+
visit[x][y] = 1;
31+
if (x == 0 || y == 0 || x == board.length - 1 || y == board[0].length - 1)return false;
32+
if (board[x - 1][y] == 'X' && board[x + 1][y] == 'X' && board[x][y - 1] == 'X' && board[x][y + 1] == 'X') {
33+
board[x][y] = 'X';
34+
return true;
35+
}
36+
boolean left = dfs(board,visit,x - 1,y);
37+
if (!left) return false;
38+
boolean right = dfs(board,visit,x + 1,y);
39+
if (!right) return false;
40+
boolean up = dfs(board,visit,x,y + 1);
41+
if (!up) return false;
42+
boolean down = dfs(board,visit,x,y - 1);
43+
if (!down) return false;
44+
45+
board[x][y] = 'X';
46+
47+
return true;
48+
}
49+
50+
public boolean legal (char [][]board, int x,int y) {
51+
int count = 0;
52+
for (int i = 0;i < y;i ++) {
53+
if (board[x][i] == 'X') count ++;
54+
}
55+
if (count < 1)return false;
56+
count = 0;
57+
for (int i = y;i < board[0].length;i ++) {
58+
if (board[x][i] == 'X') count ++;
59+
}
60+
if (count < 1)return false;
61+
for (int i = 0;i < x;i ++) {
62+
if (board[i][y] == 'X') count ++;
63+
}
64+
if (count < 1)return false;
65+
for (int i = x;i < board.length;i ++) {
66+
if (board[i][y] == 'X') count ++;
67+
}
68+
if (count < 1)return false;
69+
return true;
70+
}
71+
72+
}

0 commit comments

Comments
 (0)