200. Number of Islands
总结概括
自己对于这道题难度打分: medium,不会模板很麻烦
这道题花费的时间:30min
本题提交了几次:2
一句话评价本题:中等难度,会模板就没有问题;不同于二叉树的宽度优先搜索,这题是简单版的图像BFS。
题目分析
描述题意:给一个2Darray,求所有岛屿的数量。岛屿的意思就是connected的’1’,上下左右相连就算connected,对角线不算。
第一思路是什么:递归(错也没错,但是说宽度优先会更好)
思路过程:BFS的常规操作。
正确思路以及花费时间:巧妙运用coordinateX, coordinateY这两个数组从而免去各种(X+1)(Y),(X-1)(Y)这种对坐标进行更改的操作。
代码实现
花费时间:20min
静态查错花费多久时间:没多久
代码的可读性:good
AC Code:
class Coordinate {
int x, y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
}
class Solution {
public int numIslands(char[][] grid) {
//Check input validity
if (grid == null || grid.length == 0 || grid[0].length == 0) {
return 0;
}
int n = grid.length;
int m = grid[0].length;
int num = 0;
for (int i = 0; i < n; i++){
for (int j = 0; j < m; j++){
if(grid[i][j] == '1'){
markByBFS(grid, i, j);
num++;
}
}
}
return num;
}
private void markByBFS (char [][] grid, int x, int y){
// Magical Arrays
int [] coordinateX = {1, 0, 0, -1};
int [] coordinateY = {0, -1, 1, 0};
Queue <Coordinate> queue = new LinkedList <>();
queue.offer(new Coordinate (x, y));
grid[x][y] = '0';
while (!queue.isEmpty()){
Coordinate temp = queue.poll();
for (int i = 0; i < 4; i++){
Coordinate current = new Coordinate(temp.x + coordinateX[i],
temp.y + coordinateY[i]);
if(!inBound(grid, current.x, current.y)){
continue;
}
if(grid[current.x][current.y] == '1'){
grid[current.x][current.y] = '0';
queue.offer(current);
}
}
}
}
private boolean inBound (char [][] grid, int x, int y){
int n = grid.length;
int m = grid[0].length;
return x >= 0 && x < n && y >= 0 && y < m ;
}
}
102. Binary Tree Level Order Traversal
错误点:BFS没有分层,return value应该是分层遍历。大while是一个层,小for loop主要处理下一层(把下一层的东西压入queue中)。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList <>();
helper(res, root);
return res;
}
private void helper (List<List<Integer>> res, TreeNode root){
if (root == null){
return;
}
Queue <TreeNode> queue = new LinkedList <> ();
queue.offer(root);
while(!queue.isEmpty()){
ArrayList <Integer> level = new ArrayList <>();
int size = queue.size();
for (int i = 0; i < size; i++){
TreeNode curr = queue.poll();
level.add(curr.val);
if(curr.left != null){
queue.offer(curr.left);
}
if(curr.right != null){
queue.offer(curr.right);
}
}
res.add(level);
}
}
}
107. Binary Tree Level Order Traversal II
一次过,res.add(0, currentLevel) 无脑。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList <>();
if(root == null){
return res;
}
Queue <TreeNode> queue = new LinkedList <>();
queue.offer(root);
while(!queue.isEmpty()){
ArrayList <Integer> currentLevel = new ArrayList <>();
int size = queue.size();
for(int i = 0; i < size; i++){
TreeNode currentNode = queue.poll();
currentLevel.add(currentNode.val);
if(currentNode.left != null){
queue.offer(currentNode.left);
}
if(currentNode.right != null){
queue.offer(currentNode.right);
}
}
res.add(0, currentLevel);
}
return res;
}
}
103. Binary Tree Zigzag Level Order Traversal
二刷:BFS总是忘记level那个arraylist。。。请长脑。。。。二刷时候有一点点不会,自己就会感到非常懊恼和气愤。。。原谅一下自己吧TuT太惨了哦哦哦
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList <>();
if(root == null){
return res;
}
Stack <TreeNode> curr = new Stack <>();
Stack <TreeNode> next = new Stack <>();
Stack <TreeNode> temp;
boolean inOrder = true;
curr.push(root);
while (!curr.isEmpty()){
ArrayList <Integer> level = new ArrayList <>();
while (!curr.isEmpty()){
TreeNode currNode = curr.pop();
level.add(currNode.val);
if(inOrder){
if(currNode.left != null){
next.push(currNode.left);
}
if(currNode.right != null){
next.push(currNode.right);
}
}else{
if(currNode.right != null){
next.push(currNode.right);
}
if(currNode.left != null){
next.push(currNode.left);
}
}
}
if(inOrder){
inOrder = false;
}else{
inOrder = true;
}
res.add(level);
//Swap the stacks
temp = curr;
curr = next;
next = temp;
}
return res;
}
}
LintCode 127. Topological Sorting
二刷: BFS卡住了,忽然不记得为什么要map.put(n, map.get(n) - 1)了。其实灵魂就在于TOPOLOGICAL SORTING就是一层层地找到starting nodes。即看谁的入度先被减为0。由于我们只需要return一种排序,所以并不需要考虑其他情况。找一个(第一个入度为0)的node继续往下走就好了。
/**
* Definition for Directed graph.
* class DirectedGraphNode {
* int label;
* ArrayList<DirectedGraphNode> neighbors;
* DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
* };
*/
public class Solution {
/*
* @param graph: A list of Directed graph node
* @return: Any topological order for the given graph.
*/
public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
// write your code here
ArrayList<DirectedGraphNode> res = new ArrayList<>();
if (graph == null){
return res;
}
// Find every node's in-degree
//map : node -> in-degree
Map <DirectedGraphNode, Integer> map = new HashMap <>();
for (DirectedGraphNode node : graph){
for (DirectedGraphNode n : node.neighbors){
if (map.containsKey(n)){
map.put(n, map.get(n) + 1);
}else{
map.put(n, 1);
}
}
}
//Find all starting nodes
Queue <DirectedGraphNode> queue = new LinkedList <>();
for(DirectedGraphNode node : graph){
if(!map.containsKey(node)){
queue.offer(node);
//Starting nodes can form a topological sorting
res.add(node);
}
}
//implementing BFS
while(!queue.isEmpty()){
DirectedGraphNode current = queue.poll();
for (DirectedGraphNode n : current.neighbors){
map.put(n, map.get(n) - 1); //Decreasing the in-degree
if (map.get(n) == 0){ //in-degree -> can be a starting node
res.add(n);
queue.offer(n);
}
}
}
return res;
}
}
LintCode 618. Search Graph Nodes (locked)
Description
Given a undirected graph, a node and a target, return the nearest node to given node which value of it is target, return NULL if you can’t find.
There is a mapping store the nodes’ values in the given parameters.
Notice
It’s guaranteed there is only one available solution
一刷:
/**
* Definition for graph node.
* class UndirectedGraphNode {
* int label;
* ArrayList<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) {
* label = x; neighbors = new ArrayList<UndirectedGraphNode>();
* }
* };
*/
public class Solution {
/**
* @param graph a list of Undirected graph node
* @param values a hash mapping, <UndirectedGraphNode, (int)value>
* @param node an Undirected graph node
* @param target an integer
* @return the a node
*/
public UndirectedGraphNode searchNode(ArrayList<UndirectedGraphNode> graph,
Map<UndirectedGraphNode, Integer> values,
UndirectedGraphNode node,
int target) {
// Write your code here
if (graph == null || graph.size() == 0){
return null;
}
//BFS
Queue <UndirectedGraphNode> queue = new LinkedList <>();
//Set 用于记录这个node有没有别访问过
set <UndirectedGraphNode> set = new HashSet <>();
queue.offer(node);
set.add(node);
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++){
UndirectedGraphNode n = queue.poll();
if (n.lable == target){
return n;
}
for (UndirectedGraphNode nei : n.neighbors){
if (!set.contains(nei)){
set.add(nei);
queue.offer(nei);
}
}
}
}
return null;
}
}
LintCode 137. Clone Graph
Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
一刷:
总结概括
自己对于这道题难度打分: medium,不会模板很麻烦
这道题花费的时间:30min
本题提交了几次:2
一句话评价本题:中等难度,会模板就没有问题;不同于二叉树的宽度优先搜索,这题是简单版的图像BFS。
题目分析
描述题意:克隆一个graph,要求deep copying,意味着必须一个一个node去copy。
第一思路是什么:BFS
思路过程:BFS遍历图像
正确思路以及花费时间:用一个arraylist记录所有nodes(1st step: BFS),然后一个map产生老node和新node对应的关系(类似parallel的那种)(2nd step),要make sure每个node的edge都和原graph一致,就必须一个个地copy(3rd step)。
代码实现
花费时间:1 hr
静态查错花费多久时间:LeetCode版本不知道怎么实现deep copying。。下次回来看。LintCode是ok的。
代码的可读性:good
/**
* Definition for Undirected graph.
* class UndirectedGraphNode {
* int label;
* List<UndirectedGraphNode> neighbors;
* UndirectedGraphNode(int x) {
* label = x;
* neighbors = new ArrayList<UndirectedGraphNode>();
* }
* }
*/
public class Solution {
/**
* @param node: A undirected graph node
* @return: A undirected graph node
*/
public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
// write your code here
if (node == null){
return node;
}
//Getting all all of the nodes
ArrayList <UndirectedGraphNode> allNodes = bfs(node);
// Copying the nodes
Map <UndirectedGraphNode, UndirectedGraphNode> map = new HashMap <>();
for (UndirectedGraphNode n : allNodes){
map.put(n, new UndirectedGraphNode(n.label));
}
// Copying the neighbors
for (UndirectedGraphNode n : allNodes){
UndirectedGraphNode newNode = map.get(n);
for (UndirectedGraphNode nei : n.neighbors){
UndirectedGraphNode newNeighbor = map.get(nei);
newNode.neighbors.add(newNeighbor);
}
}
return map.get(node);
}
private ArrayList<UndirectedGraphNode> bfs (UndirectedGraphNode node){
Queue <UndirectedGraphNode> queue = new LinkedList <>();
Set <UndirectedGraphNode> set = new HashSet <>();
queue.offer(node);
set.add(node);
while(!queue.isEmpty()){
UndirectedGraphNode curr = queue.poll();
for (UndirectedGraphNode n : curr.neighbors){
if (!set.contains(n)){
set.add(n);
queue.offer(n);
}
}
}
return new ArrayList <UndirectedGraphNode> (set);
}
}
===============================
未完成:
Zombie In Matrix
Graph Valid Tree (locked)
Knight Shortest Path
Build Post Office
https://www.lintcode.com/problem/build-post-office-ii/description