EPI(Elements of Programming Interviews) 6.25 Post ions attacked by Rook
When the space usage is limited, we can consider to use and update the original input.
public static void rookAttack(int[][] A) {
int m = A.length, n = A[0].length;
boolean hasFirstRowZero = false;
for (int j = 0; j < n; ++j) {
if (A[0][j] == 0) {
hasFirstRowZero = true;
break;
}
}
boolean hasFirstColumnZero = false;
for (int[] aA : A) {
if (aA[0] == 0) {
hasFirstColumnZero = true;
break;
}
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (A[i][j] == 0) {
A[i][0] = A[0][j] = 0;
}
}
}
for (int i = 1; i < m; ++i) {
if (A[i][0] == 0) {
for (int j = 1; j < n; ++j) {
A[i][j] = 0;
}
}
}
for (int j = 1; j < n; ++j) {
if (A[0][j] == 0) {
for (int i = 1; i < m; ++i) {
A[i][j] = 0;
}
}
}
if (hasFirstRowZero) {
for (int j = 0; j < n; ++j) {
A[0][j] = 0;
}
}
if (hasFirstColumnZero) {
for (int i = 0; i < m; ++i) {
A[i][0] = 0;
}
}
}
When the space usage is limited, we can consider to use and update the original input.
public static void rookAttack(int[][] A) {
int m = A.length, n = A[0].length;
boolean hasFirstRowZero = false;
for (int j = 0; j < n; ++j) {
if (A[0][j] == 0) {
hasFirstRowZero = true;
break;
}
}
boolean hasFirstColumnZero = false;
for (int[] aA : A) {
if (aA[0] == 0) {
hasFirstColumnZero = true;
break;
}
}
for (int i = 1; i < m; ++i) {
for (int j = 1; j < n; ++j) {
if (A[i][j] == 0) {
A[i][0] = A[0][j] = 0;
}
}
}
for (int i = 1; i < m; ++i) {
if (A[i][0] == 0) {
for (int j = 1; j < n; ++j) {
A[i][j] = 0;
}
}
}
for (int j = 1; j < n; ++j) {
if (A[0][j] == 0) {
for (int i = 1; i < m; ++i) {
A[i][j] = 0;
}
}
}
if (hasFirstRowZero) {
for (int j = 0; j < n; ++j) {
A[0][j] = 0;
}
}
if (hasFirstColumnZero) {
for (int i = 0; i < m; ++i) {
A[i][0] = 0;
}
}
}