Wednesday, August 18, 2010

Microsoft Question: There exists 2D char array, We need to find out whether a given string("microsoft") exists in the given matrix. the string can be vertical or horizontal..but NOT diagonal

I think it can be achieved with straight forward recursive programming. Following is my solution --


        public bool Exist(char[][] board, string word)
        {
            for (int i = 0; i < board.Length; ++i)
            {
                for (int j = 0; j < board[0].Length; ++j)
                {
                    if (board[i][j] == word[0])
                    {
                        if (this.Search(board, i, j, word, 0))
                        {
                            return true;
                        }
                    }
                }
            }

            return false;
        }

        private bool Search(char[][] board, int i, int j, string word, int currIndex)
        {
            if (currIndex == word.Length)
            {
                return true;
            }

            if (!this.Check(board, i, j, word[currIndex]))
            {
                return false;
            }
            
            char temp = board[i][j];

            board[i][j] = '#';

            bool result = this.Search(board, i - 1, j, word, currIndex + 1) ||
                this.Search(board, i + 1, j, word, currIndex + 1) ||
                this.Search(board, i, j - 1, word, currIndex + 1) ||
                this.Search(board, i, j + 1, word, currIndex + 1);

            board[i][j] = temp;

            return result;
        }


        private bool Check(char[][] board, int i, int j, char ch)
        {
            if (i >= 0 && i < board.Length && j >= 0 && j < board[0].Length && board[i][j] == ch)
                return true;
            return false;
        }

2 comments:

  1. sir, in this problem string can be either vertical only or horizontal only. this program is serching string as
    "|m| a a a a a a a a",
    "|i| a a t a a a a a",
    "|c| r a f a a a a a",
    "|r| s s o f t a a a",
    "|o||s| a a a a a a a",
    " t |o||f|a a a a a a",
    " o a |t|a a a a a a",
    " f a a a a a a a a",
    " t a a a a a a a a",
    " a a a a a a a a a"

    ReplyDelete
  2. Again there is mistake in Problem Statement.
    Thanks for mentioning it.

    ReplyDelete