Pagini recente » Cod sursa (job #1459023) | Cod sursa (job #976311) | Cod sursa (job #1459300) | Cod sursa (job #410694) | Cod sursa (job #2972219)
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class Main {
public static int flip(int[][] board, boolean[] row, boolean[] col, int i, int j, int sum) {
if (i == board.length) {
return sum;
}
int nexti = i, nextj = j + 1;
if (nextj == board[0].length) {
nexti++;
nextj = 0;
}
int ans = flip(board, row, col, nexti, nextj, sum);
if (i == 0 || j == 0 || row[i] || col[j]) {
row[i] = !row[i];
col[j] = !col[j];
if (row[i]) {
sum += 2 * board[i][j];
} else {
sum -= 2 * board[i][j];
}
ans = Math.max(ans, flip(board, row, col, nexti, nextj, sum));
row[i] = !row[i];
col[j] = !col[j];
if (row[i]) {
sum -= 2 * board[i][j];
} else {
sum += 2 * board[i][j];
}
}
return ans;
}
public static void main(String[] args) throws IOException {
// Read input
BufferedReader br = new BufferedReader(new FileReader("flip.in"));
String[] line = br.readLine().split(" ");
int n = Integer.parseInt(line[0]);
int m = Integer.parseInt(line[1]);
int[][] board = new int[n][m];
for (int i = 0; i < n; i++) {
line = br.readLine().split(" ");
for (int j = 0; j < m; j++) {
board[i][j] = Integer.parseInt(line[j]);
}
}
br.close();
// Initialize row and col arrays to keep track of which rows and columns have been flipped
boolean[] row = new boolean[n];
boolean[] col = new boolean[m];
// Call the flip function and get the maximum sum
int maxSum = flip(board, row, col, 0, 0, 0);
// Write output
BufferedWriter bw = new BufferedWriter(new FileWriter("flip.out"));
bw.write(Integer.toString(maxSum));
bw.newLine();
bw.close();
}
}