If you met Stack Overflow and no logic problem in your code, please look at here.


  • 0
    S

    Please pay attention to the boundary condition, if you use r > 0, c > 0, r < board.length - 1, board[0].length - 1, the stack overflow exception will occur.

        private void helper(char[][] board, int r, int c) {
            if (board[r][c] == 'O') {
                board[r][c] = 'V';
                if (r > 1) helper(board, r - 1, c);
                if (c > 1) helper(board, r, c - 1);
                if (r < board.length - 2) helper(board, r + 1, c);
                if (c < board[0].length - 2) helper(board, r, c + 1);
            }
        }
    
    

    Complete code is here, my original code is a little bit different(same idea), but to find the reason of stack overflow exception, I changed it follows @Izana 's solution.

    public class Solution {
        
        public void solve(char[][] board) {
            int m = board.length;
            if (m == 0) return;
            int n = board[0].length;
            if (n == 0) return;
            for (int i = 0; i < m; i++) {
                if (board[i][0] == 'O') helper(board, i, 0);
                if (board[i][n - 1] == 'O') helper(board, i, n - 1);
            }
            for (int j = 1; j < n - 1; j++) {
                if (board[0][j] == 'O') helper(board, 0, j);
                if (board[m - 1][j] == 'O') helper(board, m - 1, j);
            }
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (board[i][j] == 'V') board[i][j] = 'O';
                    else board[i][j] = 'X';
                }
            }
        }
        
        private void helper(char[][] board, int r, int c) {
            if (board[r][c] == 'O') {
                board[r][c] = 'V';
                if (r > 1) helper(board, r - 1, c);
                if (c > 1) helper(board, r, c - 1);
                if (r < board.length - 2) helper(board, r + 1, c);
                if (c < board[0].length - 2) helper(board, r, c + 1);
            }
        }
    }
    

  • 0

    Yeah, it's weird. Looking for an answer. : )


  • 0
    S

    @Izana Might because with the old set of boundaries we need an extra stack and it causes the overflow?

    I like your profile photo, but I am big fan of Ayanami.


  • 0

    @steve.scott.509511 I guess so XD. Thank you, the voice of Ayanami is the most charming, and I like her too :-)


Log in to reply
 

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