Why do i get StackOverFlow , any suggestion to improve me solution?


  • 0
    C

    my solution is based on DFS technique

    public class Solution {
        int n,m;
        char [][] p;
        public void solve(char[][] board) {
            n = board.length;
            if(n==0)return;
            m = board[0].length;
            if(m==0)return;
            p = board;
            for(int i = 1 ; i < n-1 ; i++)
                for(int j = 1 ; j < m-1 ; j++)
                    if(p[i][j]=='O')
                        backTrack(i , j);
        }
        public boolean backTrack( int i , int j){
            if(!valid(i,j))return false;
            if(p[i][j]=='X'||p[i][j]=='.')return true;
            if(!valid(i+1,j)||!valid(i,j+1)||!valid(i-1,j)||!valid(i,j-1))return false;
            p[i][j] = '.';
            if(backTrack(i+1,j)&&backTrack(i,j+1)&&backTrack(i-1,j)&&backTrack(i,j-1))
                {
                    p[i][j] = 'X';
                    return true;
                }else{
                    p[i][j]='O';
                    return false;
                }
        }
        public boolean valid(int i , int j){
            return i>=0&&j>=0&&i<n&&j<m;
        }
    }

  • 0
    R

    Use BFS instead of DFS.


  • 0
    C

    why?
    and do you have any readable code?


  • 0
    J

    Do not use recursive function. Use your own stack, please. BFS or DFS is ok.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.