LeetCode (823) - flip image

Article Directory

topic

832. Flip the image
Given a binary matrix A, we want to flip the image horizontally first, then invert the image and return the result.
To flip a picture horizontally is to flip each line of the picture, that is, reverse the order. For example, the result of horizontally flipping [1, 1, 0] is [0, 1, 1].
Inverting the picture means that all 0s in the picture are replaced by 1s, and all 1s are replaced by 0s. For example, the result of reversing [0, 1, 1] is [1, 0, 0].

Example 1:

输入:[[1,1,0],[1,0,1],[0,0,0]]
输出:[[1,0,0],[0,1,0],[1,1,1]]
解释:首先翻转每一行: [[0,1,1],[1,0,1],[0,0,0]];
     然后反转图片: [[1,0,0],[0,1,0],[1,1,1]]

Example 2:

输入:[[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]
输出:[[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]
解释:首先翻转每一行: [[0,0,1,1],[1,0,0,1],[1,1,1,0],[0,1,0,1]];
     然后反转图片: [[1,1,0,0],[0,1,1,0],[0,0,0,1],[1,0,1,0]]

prompt:

1 <= A.length = A[0].length <= 20
0 <= A[i][j] <= 1

Solution (Java)

Flip each line first, then invert the picture, change all 0s to 1, and 1 to 0.

class Solution 
{
    
    
    public int[][] flipAndInvertImage(int[][] A) 
    {
    
    
        //创建保存结果结果数组
        int[][] result = new int[A.length][A[0].length];
        //翻转每一行
        for(int index = 0;index < A.length;index++)
        {
    
    
            int colIndex = 0;
            for(int scan = A[index].length - 1;scan >= 0;scan--)
            {
    
    
                result[index][colIndex++] = A[index][scan];
            }
        }
        //反转图片
        for(int index = 0;index < result.length;index++)
        {
    
    
            for(int scan = 0;scan < result[index].length;scan++)
            {
    
    
                if(result[index][scan] == 0)
                {
    
    
                    result[index][scan] = 1;
                }
                else if(result[index][scan] == 1)
                {
    
    
                    result[index][scan] = 0;
                }
            }
        }
        return result;
    }
}

Guess you like

Origin blog.csdn.net/weixin_46841376/article/details/114012314