英文:
Fiinding consecutive available free seats in cinema java
问题
这是我的代码:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // 行数
int m = scanner.nextInt(); // 每行座位数
int[][] cinema = new int[n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cinema[i][j] = scanner.nextInt();
}
}
int k = scanner.nextInt(); // 连续可用座位数
boolean consec = false;
int fff = 0; // 找到的第一行有连续空座位
for (int i = 0; i < n; i++) {
int cfs = 0; // 当前行的连续空座位数
for (int j = 0; j < m; j++) {
if (cinema[i][j] == 0) {
cfs++;
} else if (cinema[i][j] == 1) {
cfs = 0;
}
if (cfs == k) {
consec = true;
fff = i + 1;
break; // 找到后立即跳出循环
}
}
if (consec) {
break; // 找到后立即跳出循环
}
}
if (consec) {
System.out.println(fff);
} else {
System.out.println(0);
}
}
}
主要更改如下:
- 将
Boolean
改为boolean
,Java 中的布尔类型小写。 - 将
<
和>
替换为<
和>
。 - 添加了在找到连续座位后立即跳出两个循环的
break
语句,以及在找到后立即跳出外层循环的break
语句。这确保了在找到符合条件的座位后立即停止查找,避免输出错误的行数。
英文:
so I'm given a 2d array of n by m size and a consecutive number of free seats that I have to find in it and output the first line I find it on.
Elements in the 2d array consist of 1s and 0s, 1 is for occupied, 0 for free.
I managed to solve it 95% id say... my problem is that my code keeps outputing the last row that it finds the free consecutive seats in and not the first one...
This is my code:
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt(); // nr. of rows
int m = scanner.nextInt(); // nr. of seats / row
int[][] cinema = new int [n][m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cinema[i][j] = scanner.nextInt();
}
}
int k = scanner.nextInt(); // nr. of consecutive available seats
Boolean consec = false;
int fff = 0; // final free consecutive seats found
for (int i = 0; i < n; i++) {
int cfs = 0; // current free seat / row
for (int j = 0; j < m; j++) {
if (cinema[i][j] == 0) {
cfs++;
} else if (cinema[i][j] == 1) {
cfs = 0;
}
if (cfs == k) {
consec = true;
fff = i + 1;
} else if (fff == 0) {
consec = false;
}
}
}
if (consec) {
System.out.println(fff);
} else System.out.println(0);
}
}
What am I doing wrong?
专注分享java语言的经验与见解,让所有开发者获益!
评论