(SPOJ) Costa - Solution
Link to the problem: http://br.spoj.com/problems/COSTA12/
For every position that is corresponding to ground, the solution below checks if this position is surrounded by water or nothing.
import java.io.*;
import java.util.*;
class Main {
public char[][] matrix;
public int[] vi = {-1,0,0,1};
public int[] vj = {0,-1,1,0};
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = br.readLine();
String[] s = line.split(" ");
int numRows = Integer.parseInt(s[0]);
int numCols = Integer.parseInt(s[1]);
matrix = new char[numRows][numCols];
for (int i = 0; i < numRows; i++) {
line = br.readLine();
for (int j = 0; j < numCols; j++) {
matrix[i][j] = line.charAt(j);
}
}
int countCoast = 0;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (matrix[i][j] == '#') {
for (int k = 0; k < 4; k++) {
int nextI = i+vi[k];
int nextJ = j+vj[k];
if ((nextI < 0 || nextJ < 0 || nextI >= numRows || nextJ >= numCols) ||
(nextI >= 0 && nextJ >= 0 && nextI < numRows && nextJ < numCols && matrix[nextI][nextJ] == '.')) {
countCoast++;
break;
}
}
}
}
}
bw.write(countCoast+"\n");
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
For every position that is corresponding to ground, the solution below checks if this position is surrounded by water or nothing.
import java.io.*;
import java.util.*;
class Main {
public char[][] matrix;
public int[] vi = {-1,0,0,1};
public int[] vj = {0,-1,1,0};
public void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String line = br.readLine();
String[] s = line.split(" ");
int numRows = Integer.parseInt(s[0]);
int numCols = Integer.parseInt(s[1]);
matrix = new char[numRows][numCols];
for (int i = 0; i < numRows; i++) {
line = br.readLine();
for (int j = 0; j < numCols; j++) {
matrix[i][j] = line.charAt(j);
}
}
int countCoast = 0;
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (matrix[i][j] == '#') {
for (int k = 0; k < 4; k++) {
int nextI = i+vi[k];
int nextJ = j+vj[k];
if ((nextI < 0 || nextJ < 0 || nextI >= numRows || nextJ >= numCols) ||
(nextI >= 0 && nextJ >= 0 && nextI < numRows && nextJ < numCols && matrix[nextI][nextJ] == '.')) {
countCoast++;
break;
}
}
}
}
}
bw.write(countCoast+"\n");
bw.flush();
bw.close();
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment