gpt4 book ai didi

java - UVa 的扫雷 (10189)

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:02:43 27 4
gpt4 key购买 nike

我在解决扫雷器问题时遇到了麻烦,因为我得到的索引超出范围并且无法弄清楚原因: Here is the link of the problem

我认为我的代码效率不高,但我只想解决这个问题,这里是代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Mine_Sweepers {

public static void main(String [] args) throws IOException
{
BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));

//Taking the dimensions of the grid...

StringTokenizer s=new StringTokenizer(bf.readLine());
int b=Integer.parseInt(s.nextToken()), a=Integer.parseInt(s.nextToken());
while(b!=0 && a!=0)
{
mine(b,a);
s=new StringTokenizer(bf.readLine());
b=Integer.parseInt(s.nextToken());
a=Integer.parseInt(s.nextToken());
}
}
public static void mine(int b,int a) throws IOException
{

BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
boolean array_first=false,array_last=false,string_first=false,string_last=false;

String []x=new String[a];

for(int i=0;i<a;i++)
x[i]=bf.readLine();
for(int i=0;i<a;i++)
{
//Here I am checking whether this is the first field in the array or if it is the last
array_first=(i==0)?true:false;
array_last=(i==a-1)?true:false;
for(int j=0; j<b; j++)
{
//Here I am checking whether this is the first char in the String in the array or if it is the last
string_first=(j==0)?true:false;
string_last=(j==a-1)?true:false;
int counter=0;
if(x[i].charAt(j)!='*')
{

if(!string_first)
{
if(x[i].charAt(j-1)=='*')
counter++;
if(!array_first & x[i-1].charAt(j-1)=='*')
counter++;
if(!array_last & x[i+1].charAt(j-1)=='*')
counter++;

}
if(!string_last )
{
if(x[i].charAt(j+1)=='*')
counter++;
if(!array_first && x[i-1].charAt(j+1)=='*')
counter++;
if(!array_last & x[i+1].charAt(j+1)=='*')
counter++;
}
if(!array_first & x[i-1].charAt(j)=='*')
counter++;

if(!array_last & x[i+1].charAt(j)=='*')
counter++;

System.out.print(counter);
}
else
System.out.print('*');
}
System.out.println();
}
}

}

最佳答案

您正在使用 &does not shortcircuit .

if(!array_first & x[i-1].charAt(j+1)=='*')

所以 !array_firstx[i-1].charAt(j+1)=='*' 被求值,无论。您希望第二部分仅在第一部分评估为真时才评估,因此如果 !array_first 为假(因此 array_first 为真),则其余部分不会评估(因为如果是,i-1 将为负数,您将得到一个错误)。为此使用 &&。不仅在这条线上,而且在任何地方。

如果您使用如下模式:

if <valid indexes> and <access to those indexes>:
do work

您应该始终使用 && 作为您的逻辑 运算符。

关于java - UVa 的扫雷 (10189),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31920675/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com