LeetCode - 240. Search a 2D Matrix II

2022. 7. 24. 23:56STUDY/LeetCode

반응형

Write an efficient algorithm that searches for a value target in an m x n integer matrix matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

 

Example 1:

Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 5
Output: true

Example 2:

Input: matrix = [[1,4,7,11,15],[2,5,8,12,19],[3,6,9,16,22],[10,13,14,17,24],[18,21,23,26,30]], target = 20
Output: false

 

Constraints:

  • m == matrix.length
  • n == matrix[i].length
  • 1 <= n, m <= 300
  • -109 <= matrix[i][j] <= 109
  • All the integers in each row are sorted in ascending order.
  • All the integers in each column are sorted in ascending order.
  • -109 <= target <= 109

 이것도 Flood Fill 이랑 비슷한 문제다. 대신 시작 기준점을 어디다 배치하느냐가 관건이였다. 생각해보면 아주 간단한것인데... 

심지어 row/column 이 sorted in ascending order 도 되어있음.... !

호오 풀었도다 ㅋㅋㅋㅋ 

bool s(int** matrix, int rowSize, int colSize, int r, int c, int target)
{
    if(r < 0 || c >= colSize) return false;
    if(c < 0 || r >= rowSize) return false;
    
    int x = matrix[r][c];
    if(x == target) return true;
    
    if(x < target) {
        return s(matrix, rowSize, colSize, r+1, c, target);
    } else {
        return s(matrix, rowSize, colSize, r, c-1, target);
    }
    
    return false;
}


bool searchMatrix(int** matrix, int matrixSize, int* matrixColSize, int target){
    int r = 0;
    int c = *matrixColSize-1;
    return s(matrix, matrixSize, *matrixColSize, r, c, target);
}

 

 

728x90
반응형