Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 17, 2020 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/9a462e494fabeaea63b8dda33739b9f2 to your computer and use it in GitHub Desktop.
Save jianminchen/9a462e494fabeaea63b8dda33739b9f2 to your computer and use it in GitHub Desktop.
July 15, 2020 - 10:00 PM mock interview - interview is Microsoft SDE II, two years experience - Excellent problem solving, bug-free code
import java.io.*;
import java.util.*;
/*
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water.
Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells).
The island doesn't have "lakes" (water inside that isn't connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don't exceed 100. Determine the perimeter of the island.
Example:
Input:
3
0
3
3
2
2
3
16
[[0,2,0,0],
[2,2,2,0],
[0,2,0,0],
[2,2,0,0]]
sum = 3
3
0
3
2
3
2
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
i
i
Output: 16
http://juliachencoding.blogspot.com/2020/07/mock-interview.html
Explanation: The perimeter is the 16 yellow stripes in the image below:
*/
class Solution {
public static void main(String[] args) {
ArrayList<String> strings = new ArrayList<String>();
strings.add("Hello, World!");
strings.add("Welcome to CoderPad.");
strings.add("This pad is running Java " + Runtime.version().feature());
for (String string : strings) {
System.out.println(string);
}
}
public int islandPerimeter(int[][] grid) {
int total = 0;
if (grid == null || grid.length == 0 || grid[0].length) return total;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[0].length; j++) {
if (grid[i][j] == 1) {
int temp = 4; // take one off - it is working
temp -= neighbor(grid, i - 1, j);
temp -= neighbor(grid, i + 1, j);
temp -= neighbor(grid, i, j - 1);
temp -= neighbor(grid, i, j + 1);
total += temp;
}
}
}
return total;
}
private int neighbor(int[][] grid, int x, int y) {
return (x < 0 || x >= grid.length || y < 0 || y >= grid[0].length || grid[x][y] == 0) ? 0 : 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment