codeforces 263A(Beautiful Matrix) Java

本文介绍了一个简单的算法问题:给定一个5×5的二维数组,如何计算将其中一个非零元素移动到指定位置所需的最少步骤。通过遍历数组找到非零元素的位置,并计算其与目标位置的距离。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

还是水题,一波秒!!!

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * 题意:输入一个 5×5 二维数组,将其中一个非零数,移动到中间(即3,3)位置,一共需要多少步?
 *
 * @author TinyDolphin
 *         2017/6/24 16:30.
 */
public class Main {

    public static void main(String[] args) throws IOException {
        Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
        int positionX;  //存储非零整数的 X 坐标
        int positionY;  //存储非零整数的 Y 坐标
        int N = 5;
        while (in.hasNext()) {
            positionX = 0;
            positionY = 0;
            for (int indexI = 1; indexI <= N; indexI++) {
                for (int indexJ = 1; indexJ <= N; indexJ++) {
                    if (in.nextInt() != 0) {
                        positionX = indexJ;
                        positionY = indexI;
                    }
                }
            }
            out.println(Math.abs(positionX - 3) + Math.abs(positionY - 3));
        }
        out.flush();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值