CodeForces - 6B

本文介绍了一个Java程序,用于在一个二维字符数组中查找特定字符并计算其出现的路径。通过两个变量跟踪字符的位置,代码遍历了矩阵,计算了不重复路径上的字符数量。适合初学者理解字符串操作和数组遍历技巧。

在这里插入图片描述
题目链接

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int m = sc.nextInt();
        char u = sc.next().charAt(0);
        char[][] ch = new char[n+5][];
        for(int i=0;i<n;i++) ch[i] = sc.next().toCharArray();
        int x0 = -1;
        int y0 = -1;
        int x1 = -1;
        int y1 = -1;
        for(int i=0;i<n;i++){
            for(int j=0;j<ch[i].length;j++){
                if(x0==-1&&ch[i][j]==u){
                    x0 = i;
                    y0 = j;
                }
                if(ch[i][j]==u){
                    x1 = i;
                    y1 = j;
                }
            }
        }
        int res = 0;
        int x = x0-1;
        int y = y0;
        if(x>=0){
            if(ch[x][y]!='.') res++;
            while(y+1<=y1){
                if(ch[x][y+1]!=ch[x][y]&&ch[x][y+1]!='.') res++;
                y++;
            }
        }
        x = x1+1;
        y = y0;
        if(x<n){
            if(ch[x][y]!='.') res++;
            while(y+1<=y1){
                if(ch[x][y+1]!=ch[x][y]&&ch[x][y+1]!='.') res++;
                y++;
            }
        }
        x = x0;
        y = y0-1;
        if(y>=0){
            if(ch[x][y]!='.') res++;
            while (x+1<=x1){
                if(ch[x+1][y]!=ch[x][y]&&ch[x+1][y]!='.') res++;
                x++;
            }
        }
        x = x0;
        y = y1+1;
        if(y<ch[x].length){
            if(ch[x][y]!='.') {
                res++;
            }
            while (x+1<=x1){
                if(ch[x+1][y]!=ch[x][y]&&ch[x+1][y]!='.') res++;
                x++;
            }
        }
        System.out.println(res);
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值