【华为OD题库-058】矩阵中非1的元素个数-java

题目

存在一个m * n的二维数组,其成员取值范围为0,1,2。其中值为1的元素具备同化特性,每经过1S,将上下左右值为0的元素同化为1。而值为2的元素,免疫同化。将数组所有成员随机初始化为0或2,再将矩阵的[0,0]元素修改成1,在经过足够长的时间后求矩阵中有多少个元素是0或2(即0和2数量之和)

输入描述

输入的前两个数字是矩阵大小。后面是数字矩阵内容
输出描述

返回矩阵中非1的元素个数
示例1:
输入

4 4

0 0 0 0

0 2 2 2

0 2 0 0

0 2 0 0
输出

9
说明

输入数字前两个数字是矩阵大小。后面的数字是矩阵内容。起始位置(0,0)被修改为1后,最终只能同化矩阵为:

1 1 1 1

1 2 2 2

1 2 0 0

1 2 0 0

所以矩阵中非1的元素个数为:

9

思路

同:【华为OD题库-001】宜居星球改造计划-java

题解

java 复制代码
package hwod;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class MatrixNotOne {
    private static int[] x_axis = {0, 1, 0, -1};
    private static int[] y_axis = {1, 0, -1, 0};

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        sc.nextLine();
        int[][] nums = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                nums[i][j] = sc.nextInt();
            }
        }
        System.out.println(matrixNotOne(nums));
    }

    private static int matrixNotOne(int[][] nums) {
        int m = nums.length, n = nums[0].length;
        Queue<Integer> queue = new LinkedList<>();
        nums[0][0] = 1;
        queue.add(0);
        while (!queue.isEmpty()) {
            int cur = queue.remove();
            int x = cur / n, y = cur % n;
            for (int i = 0; i < 4; i++) {
                int new_x = x + x_axis[i];
                int new_y = y + y_axis[i];
                if (new_x >= 0 && new_x < m && new_y >= 0 && new_y < n && nums[new_x][new_y] == 0) {
                    nums[new_x][new_y] = 1;
                    queue.add(new_x * n + new_y);
                }
            }
        }
        int res = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(nums[i][j]!=1) res++;
            }
        }
        return res;
    }
}

推荐

如果你对本系列的其他题目感兴趣,可以参考华为OD机试真题及题解(JAVA),查看当前专栏更新的所有题目。

相关推荐
_深海凉_14 小时前
LeetCode热题100-搜索二维矩阵
算法·leetcode·矩阵
im_AMBER2 天前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵
Wadli2 天前
hot100|矩阵
线性代数·矩阵
呃呃本2 天前
算法题(矩阵)
线性代数·算法·矩阵
呃呃本2 天前
算法题(普通数组、矩阵)
线性代数·算法·矩阵
AI科技星2 天前
全域数学·几何本源部 第26卷 无穷几何、无穷射影几何【乖乖数学】
线性代数·矩阵
AI科技星3 天前
全域数学·第二部 几何本原部 《无穷维射影几何原本》合订典藏版【乖乖数学】
人工智能·线性代数·数学建模·矩阵·量子计算
m0_629494733 天前
LeetCode 热题 100-----18.矩阵置零
数据结构·leetcode·矩阵
youngerwang3 天前
【矩阵不是数表,而是结构的身体】
线性代数·矩阵
米饭不加菜4 天前
机器人矩阵运算MATLAB计算
matlab·矩阵·机器人