Skip to main content
edited tags
Link
mdfst13
  • 21.7k
  • 6
  • 33
  • 68
Source Link

Given a 2d matrix with chars find the target string

I am looking for a simpler implementation of the following question.

Could it get better?

I am expecting the new solution via DFS again. Thanks.

OA: Given a 2d matrix with chars and a target string.

Check if the matrix contains this target string

by only going right or down each time from the beginning point.

public class CharsIncludesString {

        static char[][] matrix = { {'a', 'b', 'c', 'd'},
                                   {'f', 'o', 'u', 'r'} ,
                                   {'r', 'r', 'p', 'c'} ,
                                   {'e', 'f', 'c', 'b'} ,
                                   {'e', 'f', 'c', 'b'}  };


    static int ROW = matrix.length;
    static int COLUMN = matrix[0].length;

    public static void main(String[] args) {

        CharsIncludesString charsIncludesString = new CharsIncludesString();

        String str = "orscb";

        System.out.println( charsIncludesString.checkStr(matrix, str) );

    }

    private boolean checkStr(char[][] matrix, String str) {

        for(int i=0;i<matrix.length;i++){
            for(int j=0;j<matrix[i].length;j++){
                if(matrix[i][j] == str.toCharArray()[0]){
                    return dfs(matrix, i, j, str.substring(1));
                }
            }
        }
        return false;
    }

    static class Cell
    {
        public int row;
        public int column;

        public Cell(int row, int column)
        {
            this.row = row;
            this.column = column;
        }
    }

    private boolean dfs(char[][] matrix, int row, int column, String str) {

        if(str.length() == 1)
            return true;

        char[] charArray = str.toCharArray();
        Boolean[][] visited = new Boolean[ROW][COLUMN];

        // Initialize a stack of pairs and
        // push the starting cell into it
        Stack<Cell> stack = new Stack<>();
        stack.push(new Cell(row, column));

        while (!stack.empty())
        {
            Cell curr = stack.pop();

            row = curr.row;
            column = curr.column;

            System.out.print(matrix[row][column] + " ");

            // Push all the adjacent cells
            char c = charArray[0];
            if(matrix[row+1][column] == c)
                dfs(matrix, row +1, column, str.substring(1));
            else if( matrix[row][column+1] == c){
                dfs(matrix, row, column+1 , str.substring(1));
            }else {
                return false;
            }
        }
        return true;
    }

}