LeetCode Brush Questions - Matrix

rotation matrix

topic

Rotate a 2D matrix 90 degrees clockwise without using extra space
Link

train of thought

First swap the elements in the matrix left and right, and then swap along the diagonal

class Solution {
    
    
    public void rotate(int[][] matrix) {
    
    
        int len = matrix.length;
        if (len == 1) {
    
    
            return;
        }
        for (int i = 0; i < len; i++) {
    
    
            for (int j = 0; j < len / 2; j++) {
    
    
                swap(matrix, i, j, i, len - j - 1);
            }
        }
        for (int i = 0; i < len; i++) {
    
    
            for (int j = 0; j < len - i; j++) {
    
    
                swap(matrix, i, j, len - j - 1, len - i -1);
            }
        }
    }

  	// 交换矩阵中的两个元素
    private void swap(int[][] matrix, int x1, int y1, int x2, int y2) {
    
    
        int tmp = matrix[x1][y1];
        matrix[x1][y1] = matrix[x2][y2];
        matrix[x2][y2] = tmp;
    }
}

Spiral matrix (print matrix clockwise)

topic

Get the elements in the matrix clockwise and return a list
link

train of thought

Define four dividing lines up, down, left, and right. When a line or a column is completed, the corresponding dividing line will move. When the two dividing lines collide, it means that the traversal is over.

class Solution {
    
    
    public List<Integer> spiralOrder(int[][] matrix) {
    
    
        int rows = matrix.length;
        int cols = matrix[0].length;
      	// 定义上、左、右、下四条分割线
        int below = 0, left = 0, right = cols - 1, bottom = rows - 1;
        List<Integer> list = new ArrayList<>();
        while (true) {
    
    
          	// 从左到右遍历
            for (int i = left; i <= right; i++) {
    
    
                list.add(matrix[below][i]);
            }
            if (below++ == bottom) {
    
    
                break;
            }
          	// 从上到下遍历
            for (int i = below; i <= bottom; i++) {
    
    
                list.add(matrix[i][right]);
            }
            if (right-- == left) {
    
    
                break;
            }
          	// 从右到左遍历
            for (int i = right; i >= left; i--) {
    
    
                list.add(matrix[bottom][i]);
            }
            if (bottom-- == below) {
    
    
                break;
            }
          	// 从下到上遍历
            for (int i = bottom; i >= below; i--) {
    
    
                list.add(matrix[i][left]);
            }
            if (left++ == right) {
    
    
                break;
            }
        }
        return list;
    }
}

paths in the matrix

topic

Given an mxn two-dimensional character grid board and a string word word. Returns true if word exists in the grid; otherwise, returns false.

Words must be formed alphabetically, through letters in adjacent cells, where "adjacent" cells are those that are horizontally or vertically adjacent. Letters in the same cell are not allowed to be used repeatedly.

Link

train of thought

Depth-first traversal, try each element in the matrix in four directions: up, down, left, and right

class Solution {
    
    
    public boolean exist(char[][] board, String word) {
    
    
        char[] words = word.toCharArray();
        for (int i = 0; i < board.length; i++) {
    
    
            for (int j = 0; j < board[0].length; j++) {
    
    
                if (dfs(board, words, i, j, 0)) {
    
    
                    return true;
                }
            }
        }
        return false;
    }
	
	// k记录成功匹配的字母个数
    private boolean dfs(char[][] board, char[] words, int i, int j, int k) {
    
    
    	// 数组越界或当前字符不在目标字符串内,直接返回false
        if (i < 0 || i >= board.length || j < 0 || j >= board[0].length || board[i][j] != words[k]) {
    
    
            return false;
        }
        if (words.length == k + 1) {
    
    
            return true;
        }
        // 更改值表示当前位置已访问过
        board[i][j] = '\0';
        boolean res = dfs(board, words, i + 1, j, k + 1) || dfs(board, words, i - 1, j, k + 1) || dfs(board, words, i, j + 1, k + 1) || dfs(board, words, i, j - 1, k + 1);
        // 恢复为初始值
        board[i][j] = words[k];
        return res;
    }
}

Search 2D Matrix

topic

Determine whether there is a target value in the two-dimensional matrix, the matrix is ​​incremented for each row, and
the link is incremented for each column

train of thought

Each time compare the value in the upper right corner of the matrix with the target value, if the value is greater than the target value, it means that the target value is in the row; if the value is smaller than the target value, exclude the current row, and repeat until the target value is found

class Solution {
    
    
    public boolean searchMatrix(int[][] matrix, int target) {
    
    
        int row = matrix.length;
        int col = matrix[0].length;
        int r = 0, c = col - 1;
        while (r < row && c >= 0) {
    
    
            if (matrix[r][c] == target) {
    
    
                return true;
            } else if (matrix[r][c] > target) {
    
    
                c--;
            } else {
    
    
                r++;
            }
        }
        return false;
    }
}

matrix zeroing

topic

Given a two-dimensional matrix, if an element is 0, all elements in the corresponding row and column must be changed to 0, please modify the matrix
link in place

train of thought

Traverse all elements of the matrix except the first row and first column. If an element is 0, change the value of the corresponding first row and first column position to 0, which is equivalent to a mark, indicating the corresponding row and column Subsequent changes must be changed to 0; but the first row and the first column may already have 0, which will conflict with the mark, so the first row and first column must be traversed first, and two Boolean variables are used to record the first row and the first row. Whether a column should be zeroed

class Solution {
    
    
    public void setZeroes(int[][] matrix) {
    
    
    	// 记录第一行和第一列是否要置为0
        boolean rowZero = false;
        boolean colZero = false;
        int i = 0, j = 0;
        for (i = 0; i < matrix[0].length; i++) {
    
    
            if (matrix[0][i] == 0) {
    
    
                rowZero = true;
                break;
            }
        }
        for (j = 0; j < matrix.length; j++) {
    
    
            if (matrix[j][0] == 0) {
    
    
                colZero = true;
                break;
            }
        }
        for (i = 1; i < matrix.length; i++) {
    
    
            for (j = 1; j < matrix[0].length; j++) {
    
    
            	// 若某元素为0,将第一行和第一列的对应位置置为0,相当于标记
                if (matrix[i][j] == 0) {
    
    
                    matrix[i][0] = 0;
                    matrix[0][j] = 0;
                }
            }
        }
        for (i = 1; i < matrix.length; i++) {
    
    
            for (j = 1; j < matrix[0].length; j++) {
    
    
            	// 根据标记对相应的行和列置零
                if (matrix[i][0] == 0 || matrix[0][j] == 0) {
    
    
                    matrix[i][j] = 0;
                }
            }
        }
        // 根据布尔变量决定第一行和第一列是否置零
        if (rowZero) {
    
    
            for (i = 0; i < matrix[0].length; i++) {
    
    
                matrix[0][i] = 0;
            }
        }
        if (colZero) {
    
    
            for (j = 0; j < matrix.length; j++) {
    
    
                matrix[j][0] = 0;
            }
        }
    }
}

Guess you like

Origin blog.csdn.net/wzc3614/article/details/129570411