首页 > 代码库 > 【leetcode】com/problems/surrounded-regions/

【leetcode】com/problems/surrounded-regions/

dfs 栈溢出,bfs超时,用dfs非递归就不溢出了,前后写了1一个星期
class node{ int i; int j; public node(int i1,int j1) { i=i1; j=j1; }} public class Solution { public void solve(char[][] board) { int len1=board.length; if(len1<=0)return; int len2=board[0].length; if(len1<=2||len2<=2) return; for(int i=0;i<len1;i++) { if(board[i][0]==‘O‘) dfs(board,i,0); if(board[i][len2-1]==‘O‘) dfs(board,i,len2-1); } for(int i=0;i<len2;i++) { if(board[0][i]==‘O‘)dfs(board,0,i); if(board[len1-1][i]==‘O‘)dfs(board,len1-1,i); } for(int i=0;i<len1;i++) { for(int j=0;j<len2;j++) { if(board[i][j]==‘h‘) board[i][j]=‘O‘; else board[i][j]=‘X‘; } } } public boolean is(int i,int j,int len1,int len2) { if(i>=0&&i<len1&&j>=0&&j<len2) return true; return false; } public void dfs(char b[][],int i,int j) { int len1=b.length; int len2=b[0].length; Stack<node> s=new Stack<node>(); b[i][j]=‘h‘; s.push(new node(i,j)); }}