问题陈述
您将看到一个多层机架,其形式为一个m行n列的矩阵。每个单元格由红色药丸(用r标记)、蓝色药片(用b表示)或细菌(用x表示)占据。红色药丸可以杀死水平、垂直和对角方向的相邻细菌(如果有的话),而蓝色药丸只能杀死水平和垂直方向的相邻细菌(如果有的话)。最初,这些药片是无效的。一旦被激活,它们就可以作用于相邻的细菌。一旦药片被激活,你需要找出架子上剩余细菌的数量。
M=行n=列,test =迭代次数
R=红色药丸,
X=细菌
条件包括:
R=红色药丸可在水平、垂直和对角方向上杀灭相邻的细菌。
我需要找到剩下的细菌。
我的(不完整的)解决方案是-我创建了一个接受字符串的2d数组(Arr1),然后将该数组元素转换为整数,即0&1(r=0和x= 1),并存储在另一个2d数组(Arr2)中。现在我只能计算细菌的总数,但我想找到剩余的细菌。
这是我的代码
import java.util.Scanner;
import java.*;
public class Pills {
public static void main(String args[])
{
// initialize here.
int row, col, i, j, k, test;
String arr[][] = new String[10][10];
int arr2[][] = new int[10][10];
Scanner scan = new Scanner(System.in);
System.out.println("Enter number of tests :");
test = scan.nextInt();
for(k=0;k<test;k++)
{
//enter row and column for array.
System.out.println(" ");
row = scan.nextInt();
System.out.println(" ");
col = scan.nextInt();
// enter array elements.
System.out.println(" ");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
arr[i][j] = scan.next();
if(arr[i][j].equals("r"))
{
arr2[i][j]=0;
}
else {
arr2[i][j]=1;
}
}
}
// the 2D array is here.
System.out.print("\n");
for(i=0; i<row; i++)
{
for(j=0; j<col; j++)
{
System.out.print(arr[i][j]+ " ");
}
System.out.println();
}
System.out.print("\n");
int sum = 0;
for ( i=0; i < arr2.length; i++)
{
for (j=0; j < arr2[i].length; j++)
{
sum = sum + arr2[i][j];
}
}
System.out.println("Total Germs : "+sum);
}
}
}我需要帮助找到剩下的细菌。
发布于 2019-11-13 18:30:38
public class Main
{
public static void main (String[]args)
{
String[][]arr =
{
{
"g", "g", "g", "g"},
{
"g", "r", "g", "g"},
{
"g", "g", "g", "g"},
{
"g", "g", "g", "g"}
};
int germCount = getGerms (arr);
System.out.print (germCount);
}
public static int getGerms (String[][]arr)
{
int germCount = 0;
int row = arr.length;
int col = arr[0].length;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
if (arr[i][j].equals ("r") || arr[i][j].equals ("b"))
{
if (i + 1 < row && arr[i + 1][j].equals ("g"))
{
arr[i + 1][j] = "k";
}
if (i - 1 >= 0 && arr[i - 1][j].equals ("g"))
{
arr[i - 1][j] = "k";
}
if (j + 1 < col && arr[i][j + 1].equals ("g"))
{
arr[i][j + 1] = "k";
}
if (j - 1 >= 0 && arr[i][j - 1].equals ("g"))
{
arr[i][j - 1] = "k";
}
}
if (arr[i][j].equals ("r"))
{
if (i + 1 < row && j + 1 < col
&& arr[i + 1][j + 1].equals ("g"))
{
arr[i + 1][j + 1] = "k";
}
if (i + 1 < row && j - 1 >= 0
&& arr[i + 1][j - 1].equals ("g"))
{
arr[i + 1][j - 1] = "k";
}
if (i - 1 >= 0 && j - 1 >= 0
&& arr[i - 1][j - 1].equals ("g"))
{
arr[i - 1][j - 1] = "k";
}
if (i - 1 >= 0 && j + 1 < col
&& arr[i - 1][j + 1].equals ("g"))
{
arr[i - 1][j + 1] = "k";
}
}
}
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
System.out.print (arr[i][j]);
if (arr[i][j].equals ("g"))
germCount++;
}
System.out.println ();
}
return germCount;
}
}o/p-
kkkg
krkg
kkkg
gggg
7https://stackoverflow.com/questions/57759497
复制相似问题