Search code examples
javaarraysmatrixdiagonal

Finding Diagonal of a number in 2D array?


If I have the following matrix of 5x5 lets say

{ ,  , T ,  , }
{ , T , T , , }
{ ,  , T ,  , }
{ , T,  ,  ,  }
{T,  ,  ,  ,  }

and I have to check if the char in a matrix is diagonal to another one, I am checking them in the following way,

public boolean isDiagonal(int row,int col){
    if (row == board.length-1 && board[row-1][col+1] == 'T') {
        return true;
    } else if (col == board.length -1 && board[row+1][col-1] == 'T') {
        return true;
    } else if (board[row][col] == 'T' && board[row+1][col+1] == 'T' ||     
        board[row][col] == 'T' && board[row-1][col-1] == 'T') {
        return true;
    } else if (board[row][col] == 'T' && board[row-1][col+1] == 'T' || 
        board[row][col] == 'T' && board[row+1][col-1] == 'T') {     
        return true;
    }

    return false;
}

The char T is randomly being assigned on the board. I need to check while placing the char T if there exists another T diagonally to it.

The method takes row and column and checks whether the char T exists on the board and if it is diagonal to another T.

If the row = 0 and col = 4 or row = 1 and col = 5 and so on... It is going to fail and throw array out of bounds.

What is the efficient way to get the diagonal to any number in a matrix and avoiding the edge cases?

PS: I am trying to code in Java


Solution

  • I would create a method to get the element, and that returns a default value if coordinates are invalid. Just use a default value to anything but what you search for.

    public char getWithDefault(int row, int col, char default ) {
      if ((0 <= row) && ( row < board.length) &&
          (0<=col) && (col < board[row].length)) {
        return board[row][col];
      }
      return default;
    }
    
    public boolean isDiagonal(int row,int col){
      // arbitrary default value, as long as it is != 'T'
      if (getWithDefault(row,col,'1') != 'T') return false;
      if (getWithDefault(row+1,col+1,'1') == 'T') return true;
      if (getWithDefault(row+1,col-1,'1') == 'T') return true;
      if (getWithDefault(row-1,col+1,'1') == 'T') return true;
      if (getWithDefault(row-1,col-1,'1') == 'T') return true;
      return false;
    }
    

    From your code, I deduced board is an array of array of char.