leetcode130问题,波波老师麻烦帮我分析一下,不知道哪里出了问题
来源:8-7 floodfill算法,一类经典问题 Number of Islands-
慕工程2559728
2018-08-14
boolean[][] visited; int m; int n; int[][] move = {{0,1},{-1,0},{0,-1},{1,0}}; public void solve(char[][] board) { m = board.length; if(m==0) return; n = board[0].length; visited = new boolean[m][n]; for(int i= 0 ;i<m;i++){ for(int j=0;j<n;j++){ if(board[i][j] == 'O' && !visited[i][j]){ mark(i,j,board); } } } return; } private boolean mark(int i, int j, char[][] board) { visited[i][j] = true; boolean lable = false; if(i==m-1 || j==n-1 || i==0 || j==0) lable = true; for(int k=0; k<4; k++){ int newx = i + move[k][0]; int newy = j + move[k][1]; if(inarea(newx,newy) && !visited[newx][newy] && board[newx][newy]=='O'){ lable = mark(newx,newy,board) || lable ; } if(!lable) board[i][j] = 'X'; } return lable; } private boolean inarea(int i, int j) { return i>=0 && j>=0 && i<m && j<n; }
写回答
1回答
-
130使用DFS无法ac,因为极端数据会导致栈溢出,可以参考这里的注释:)
https://github.com/liuyubobobo/Play-Leetcode/blob/master/0130-Surrounded-Regions/cpp-0130/main.cpp
改成BFS就ok了:)加油!
032020-06-23
相似问题
逆波兰问题
回答 1