Why does this code give time limit exceeded? Java


  • 0
    N
    public class Solution {
    public boolean exist(char[][] board, String word) {
        int n = board.length;
        int m = board[0].length;
        char[][] mark = new char[n][m];
        int k = word.length();
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++){
                boolean[][] used = new boolean[n][m];
                if(DFS(board,i,j,0,word,used))
                    return true;
            }
        return false;
    }
    public boolean DFS(char[][] board, int i, int j, int chAt, String word,boolean[][] used){
        if(chAt == word.length())
            return true;
        if(i<0||j<0||i>board.length-1||j>board[0].length-1)
            return false;
        if(used[i][j]==false&&board[i][j]==word.charAt(chAt))
        {
            used[i][j]=true;
            if(DFS(board, i-1,j,chAt+1,word,used))
                return true;
            if(DFS(board, i+1,j,chAt+1,word,used))
                return true;
            if(DFS(board, i,j+1,chAt+1,word,used))
                return true;
            if(DFS(board, i,j-1,chAt+1,word,used))
                return true;
            used[i][j]=false;
                
        }
        return false;
    }
    

    }


Log in to reply
 

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