Help! Why is runtime error?


  • 0
    J

    Please help me. I really don't know why it is runtime error.

    At first I thought it maybe stack overflow. However, Another person also use the DFS method and solve this problem in https://leetcode.com/discuss/42445/a-really-simple-and-readable-c-solution,only-cost-12ms.

    The idea is quite simple. First, set all the ‘O’ to 'N' from the margin of the matrix. Then, set all the 'O' to 'X' while reset the 'N' to ‘O’.

    class Solution {
    public:
        bool dfs(vector<vector<char>>& board,int x, int y) {
            board[x][y] = 'N';
            int offsetX[] = {0,1,0,-1};
            int offsetY[] = {1,0,-1,0};
            
            for (int i = 0; i < 4; i++) {
                int x1 = x + offsetX[i];
                int y1 = y + offsetY[i];
                if ( x1 >= 0 && x1 <= (int)board.size()-1 && y1 >= 0 && y1 <= (int)board[0].size()-1 && board[x1][y1] == 'O') {
                    dfs(board, x1, y1);
                }
            }
            
            return true;
        }
        void solve(vector<vector<char>>& board) {
            if (board.size() == 0 || board[0].size() == 0) return;
            
            for (int j = 0; j < board[0].size(); j++) {
                if (board[0][j] == 'O') {
                    dfs(board, 0, j);
                }
                if (board[board.size()-1][j] == 'O') {
                    dfs(board, board.size()-1, j);
                }
            }
            
            for (int i = 0; i < board.size(); i++) {
                if (board[i][0] == 'O') {
                    dfs(board, i, 0);
                }
                if (board[i][board[0].size()-1] == 'O') {
                    dfs(board, i, board[0].size()-1);
                }
            }
            
            for (int i = 0; i < board.size(); i++) {
                for (int j = 0; j < board[0].size(); j++) {
                    if (board[i][j] == 'N') board[i][j] = 'O';
                    else if (board[i][j] == 'O') board[i][j] = 'X';
                }
            }
            
        }
    };

Log in to reply
 

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