最新华为OD机试真题-反射计数 (200分)
🍭 大家好这里是清隆学长 ,一枚热爱算法的程序员
✨ 本系列打算持续跟新华为OD-C/D卷的三语言AC题解
💻 ACM银牌🥈| 多次AK大厂笔试 | 编程一对一辅导
👏 感谢大家的订阅➕ 和 喜欢💗
📎在线评测链接
🌍 评测功能需要 =>订阅专栏<= 后联系清隆解锁~
🍓OJ题目截图
🍰 反射计数
问题描述
给定一个由 0 和 1 组成的二维矩阵,以及一个初始位置和速度。有一个物体从给定的初始位置出发,以给定的速度移动。物体在矩阵边缘发生镜面反射,无论经过 0 还是 1 都不影响其速度。请计算经过 时间单位后,物体经过 1 点的次数。
注意:
- 初始位置的点是 1 时也计算在内。
- 时间的最小单位为 1,不考虑小于 1 个时间单位内经过的点。
输入格式
第一行包含七个整数 ,分别表示矩阵的宽度、高度、初始位置的列坐标、行坐标、初始速度的纵向分量、初始速度的横向分量和经过的时间。
接下来 行,每行包含
个整数,表示二维矩阵。
输出格式
一个整数,表示经过的 1 的次数。
样例输入
12 7 2 1 1 -1 13
001000010000
001000010000
001000010000
000100001000
001000010000
001000010000
001000010000
样例输出
3
数据范围
题解
从初始位置开始,在每个时间单位更新物体的位置。如果物体到达矩阵边缘,则反射其速度方向。每当物体经过一个新的位置时,检查该位置的值是否为 1,并更新计数器。
参考代码
- Python
def count_ones(w, h, y, x, sy, sx, t, matrix):
res = 0
if matrix[x][y] == "1":
res += 1
for _ in range(t):
xx = x + sx
yy = y + sy
if xx < 0 or xx >= h:
sx = -sx
if yy < 0 or yy >= w:
sy = -sy
x += sx
y += sy
if matrix[x][y] == "1":
res += 1
return res
w, h, y, x, sy, sx, t = map(int, input().split())
matrix = [list(input().strip()) for _ in range(h)]
print(count_ones(w, h, y, x, sy, sx, t, matrix))
- Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int w = sc.nextInt();
int h = sc.nextInt();
int y = sc.nextInt();
int x = sc.nextInt();
int sy = sc.nextInt();
int sx = sc.nextInt();
int t = sc.nextInt();
sc.nextLine();
char[][] matrix = new char[h][w];
for (int i = 0; i < h; i++) {
matrix[i] = sc.nextLine().toCharArray();
}
System.out.println(countOnes(w, h, y, x, sy, sx, t, matrix));
}
public static int countOnes(int w, int h, int y, int x, int sy, int sx, int t, char[][] matrix) {
int res = 0;
if (matrix[x][y] == '1') {
res += 1;
}
for (int i = 0; i < t; i++) {
int xx = x + sx;
int yy = y + sy;
if (xx < 0 || xx >= h) {
sx = -sx;
}
if (yy < 0 || yy >= w) {
sy = -sy;
}
x += sx;
y += sy;
if (matrix[x][y] == '1') {
res += 1;
}
}
return res;
}
}
- Cpp
#include <iostream>
#include <vector>
using namespace std;
int countOnes(int w, int h, int y, int x, int sy, int sx, int t, vector<vector<char>>& matrix) {
int res = 0;
if (matrix[x][y] == '1') {
res++;
}
for (int i = 0; i < t; i++) {
int xx = x + sx;
int yy = y + sy;
if (xx < 0 || xx >= h) {
sx = -sx;
}
if (yy < 0 || yy >= w) {
sy = -sy;
}
x += sx;
y += sy;
if (matrix[x][y] == '1') {
res++;
}
}
return res;
}
int main() {
int w, h, y, x, sy, sx, t;
cin >> w >> h >> y >> x >> sy >> sx >> t;
vector<vector<char>> matrix(h, vector<char>(w));
for (int i = 0; i < h; i++) {
for (int j = 0; j < w; j++) {
cin >> matrix[i][j];
}
}
cout << countOnes(w, h, y, x, sy, sx, t, matrix) << endl;
return 0;
}
#华为OD##华为od##华为od题库##华为##华为OD机试算法题库#最新华为OD机试-D卷 文章被收录于专栏
本专栏给大家提供了华为2024最新华为OD-C/D卷的题目汇总和(Java/Cpp/Python)三语言解析 + 提供OJ在线评测