Friday, September 22, 2017

[LeetCode] 433. Minimum Genetic Mutation

A gene string can be represented by an 8-character long string, with choices from "A""C""G""T".
Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
For example, "AACCGGTT" -> "AACCGGTA" is 1 mutation.
Also, there is a given gene "bank", which records all the valid gene mutations. A gene must be in the bank to make it a valid gene string.
Now, given 3 things - start, end, bank, your task is to determine what is the minimum number of mutations needed to mutate from "start" to "end". If there is no such a mutation, return -1.
Note:
  1. Starting point is assumed to be valid, so it might not be included in the bank.
  2. If multiple mutations are needed, all mutations during in the sequence must be valid.
  3. You may assume start and end string is not the same.
Example 1:
start: "AACCGGTT"
end:   "AACCGGTA"
bank: ["AACCGGTA"]

return: 1
Example 2:
start: "AACCGGTT"
end:   "AAACGGTA"
bank: ["AACCGGTA", "AACCGCTA", "AAACGGTA"]

return: 2
Example 3:
start: "AAAAACCC"
end:   "AACCCCCC"
bank: ["AAAACCCC", "AAACCCCC", "AACCCCCC"]

return: 3

Code:
public class Solution {
    public int minMutation(String start, String end, String[] bank) {
        if(start.equals(end)) return 0;
        
        Set<String> bankSet = new HashSet<>();
        for(String b: bank) bankSet.add(b);
        
        char[] charSet = new char[]{'A', 'C', 'G', 'T'};
        
        int level = 0;
        Set<String> visited = new HashSet<>();
        Queue<String> queue = new LinkedList<>();
        queue.offer(start);
        visited.add(start);
        
        while(!queue.isEmpty()) {
            int size = queue.size();
            while(size-- > 0) {
                String curr = queue.poll();
                if(curr.equals(end)) return level;
                
                char[] currArray = curr.toCharArray();
                for(int i = 0; i < currArray.length; i++) {
                    char old = currArray[i];
                    for(char c: charSet) {
                        currArray[i] = c;
                        String next = new String(currArray);
                        if(!visited.contains(next) && bankSet.contains(next)) {
                            visited.add(next);
                            queue.offer(next);
                        }
                    }
                    currArray[i] = old;
                }
            }
            level++;
        }
        return -1;
    }
}

Monday, September 18, 2017

[LeetCode] 505. The Maze II

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling updownleft or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, find the shortest distance for the ball to stop at the destination. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the destination (included). If the ball cannot stop at the destination, return -1.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.
Example 1
Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)

Output: 12
Explanation: One shortest way is : left -> down -> left -> down -> right -> down -> right.
             The total distance is 1 + 1 + 3 + 1 + 2 + 2 + 2 = 12.

Example 2
Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2)

Output: -1
Explanation: There is no way for the ball to stop at the destination.

Code:
public class Solution { class Point { int x,y,l; public Point(int _x, int _y, int _l) {x=_x;y=_y;l=_l;} } public int shortestDistance(int[][] maze, int[] start, int[] destination) { int m=maze.length, n=maze[0].length; int[][] length=new int[m][n]; // record length for (int i=0;i<m*n;i++) length[i/n][i%n]=Integer.MAX_VALUE; int[][] dir=new int[][] {{-1,0},{0,1},{1,0},{0,-1}}; PriorityQueue<Point> list=new PriorityQueue<>((o1,o2)->o1.l-o2.l); // using priority queue list.offer(new Point(start[0], start[1], 0)); while (!list.isEmpty()) { Point p=list.poll(); if (length[p.x][p.y]<=p.l) continue; // if we have already found a route shorter length[p.x][p.y]=p.l; for (int i=0;i<4;i++) { int xx=p.x, yy=p.y, l=p.l; while (xx>=0 && xx<m && yy>=0 && yy<n && maze[xx][yy]==0) { xx+=dir[i][0]; yy+=dir[i][1]; l++; } xx-=dir[i][0]; yy-=dir[i][1]; l--; list.offer(new Point(xx, yy, l)); } } return length[destination[0]][destination[1]]==Integer.MAX_VALUE?-1:length[destination[0]][destination[1]]; } }

[LeetCode] 490. The Maze

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling updownleft or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.
Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.
The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The start and destination coordinates are represented by row and column indexes.
Example 1
Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)

Output: true
Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.

Example 2
Input 1: a maze represented by a 2D array

0 0 1 0 0
0 0 0 0 0
0 0 0 1 0
1 1 0 1 1
0 0 0 0 0

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2)

Output: false
Explanation: There is no way for the ball to stop at the destination.

Code:public class Solution {
class Point { int x,y; public Point(int _x, int _y) {x=_x;y=_y;} } public boolean hasPath(int[][] maze, int[] start, int[] destination) { int m=maze.length, n=maze[0].length; if (start[0]==destination[0] && start[1]==destination[1]) return true; int[][] dir=new int[][] {{-1,0},{0,1},{1,0},{0,-1}}; boolean[][] visited=new boolean[m][n]; LinkedList<Point> list=new LinkedList<>(); visited[start[0]][start[1]]=true; list.offer(new Point(start[0], start[1])); while (!list.isEmpty()) { Point p=list.poll(); int x=p.x, y=p.y; for (int i=0;i<4;i++) { int xx=x, yy=y; while (xx>=0 && xx<m && yy>=0 && yy<n && maze[xx][yy]==0) { xx+=dir[i][0]; yy+=dir[i][1]; } xx-=dir[i][0]; yy-=dir[i][1]; if (visited[xx][yy]) continue; visited[xx][yy]=true; if (xx==destination[0] && yy==destination[1]) return true; list.offer(new Point(xx, yy)); } } return false; } }

Sunday, September 17, 2017

[LeetCode] 130. Surrounded Regions

Given a 2D board containing 'X' and 'O' (the letter O), capture all regions surrounded by 'X'.
A region is captured by flipping all 'O's into 'X's in that surrounded region.
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X

Code:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40