需要打开多少监控器

题目描述

某长方形停车场,每个车位上方都有对应监控器,当且仅当在当前车位或者前后左右四个方向任意一个车位范围停车时,监控器才需要打开
给出某一时刻停车场的停车分布,请统计最少需要打开多少个监控器;

输入描述:

第一行输入m,n表示长宽,满足1 < m,n <= 20;
后面输入m行,每行有n个0或1的整数,整数间使用一个空格隔开,表示该行已停车情况,其中0表示空位,1表示已停:

输出描述:

最少需要打开监控器的数量

示例1

输入

3 3

0 0 0

0 1 0

0 0 0

输出

5
示例2:

输入输出示例仅供调试,后台判题数据一般不包含示例

输入

3 4

0 0 0 0

0 1 0 1

0 0 0 0

输出

8

题目解析

解题思路

①数据存储方式 数组形式存储
②数据处理方式 判断周围是否有车

代码实现

package com.HW;

import javax.swing.*;
import java.io.PrintStream;
import java.sql.SQLOutput;
import java.util.Arrays;
import java.util.Locale;

/**
 * @ClassName : TCarMonitor
 * @Author : kele
 * @Date: 2023/10/22 17:24
 * @Description : 需要打开多少监视器
 */
public class TCarMonitor {

    public static void main(String[] args) {

        handle("3 4", "0 0 0 0", "0 1 0 1", "0 0 0 0");
        handle("3 3", "0 0 0", "0 1 0", "0 0 0");

    }

    public static void handle(String coordinate, String... car) {

        String[] s = coordinate.split(" ");
        int x = Integer.parseInt(s[0]);
        int y = Integer.parseInt(s[1]);
        int[][] location = new int[x][y];

        for (int i = 0; i < x; i++) {
            String[] line = car[i].split(" ");
            for (int j = 0; j < line.length; j++) {
                location[i][j] = Integer.parseInt(line[j]);
            }
        }
        //需要开启监控器的总数
        int num = 0;
        //遍历各个车位
        for (int i = 0; i < location.length; i++) {
            for (int j = 0; j < location[0].length; j++) {
                if (isMonitor(i, j, location)) {
                    num ++;
                }
            }
        }

        System.out.println(num);

    }

//判断该位置是否需要开监控器
    public static boolean isMonitor(int x, int y, int[][] location) {

        int[][] actions = new int[][]{{0, 0}, {1, 0}, {0, 1}, {-1, 0}, {0, -1}};

        for (int[] action : actions) {

            int x_a = x + action[0];
            int y_a = y + action[1];

            if (x_a >= 0 && y_a >= 0 && x_a < location.length && y_a < location[0].length) {
                if (location[x_a][y_a] == 1) {
                    return true;
                }
            }
        }
        return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值