2/28/2013

Surrounded Regions

Surrounded RegionsFeb 22
Given a 2D board containing 'X' and '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
Idea: BFS

  1. class Solution {
  2. public:
  3. void solve(vector<vector<char>> &board) {
  4. // Start typing your C/C++ solution below
  5. // DO NOT write int main() function
  6. if (board.size() <= 1) return;
  7. int rows = board.size();
  8. int cols = board[0].size();
  9. vector<vector<bool>> visited(rows, vector<bool>(cols, false));
  10. vector<vector<bool>> checked(rows, vector<bool>(cols, false));
  11. for (int i = 0; i < rows; ++i) {
  12. for (int j = 0; j < cols; ++j) {
  13. if (!visited[i][j]) {
  14. if (board[i][j] == 'O') {
  15. if (checkIfSurrounded(i, j, board, visited, checked)) {
  16. markChecked(i, j, board, checked);
  17. }
  18. }
  19. else {
  20. visited[i][j] = true;
  21. }
  22. }
  23. }
  24. }
  25. }
  26. bool checkIfSurrounded(int i, int j, vector<vector<char>> &board,
  27. vector<vector<bool>> &visited, vector<vector<bool>> &checked) {
  28. queue<Pos> q;
  29. bool result = true;
  30. q.push(Pos(i, j));
  31. visited[i][j] = true;
  32. while (!q.empty()) {
  33. Pos pos = q.front();
  34. q.pop();
  35. i = pos.row;
  36. j = pos.col;
  37. checked[i][j] = true;
  38. if (j - 1 >= 0) {
  39. if (board[i][j - 1] == 'O' && !visited[i][j - 1]) {
  40. q.push(Pos(i, j - 1));
  41. visited[i][j - 1] = true;
  42. }
  43. }
  44. else {
  45. result = false;
  46. }
  47. if (j + 1 < board[0].size()) {
  48. if (board[i][j + 1] == 'O' && !visited[i][j + 1]) {
  49. q.push(Pos(i, j + 1));
  50. visited[i][j + 1] = true;
  51. }
  52. }
  53. else {
  54. result = false;
  55. }
  56. if (i + 1 < board.size()) {
  57. if (board[i + 1][j] == 'O' && !visited[i + 1][j]) {
  58. q.push(Pos(i + 1, j));
  59. visited[i + 1][j] = true;
  60. }
  61. }
  62. else {
  63. result = false;
  64. }
  65. if (i - 1 >= 0) {
  66. if (board[i - 1][j] == 'O' && !visited[i - 1][j]) {
  67. q.push(Pos(i - 1, j));
  68. visited[i - 1][j] = true;
  69. }
  70. }
  71. else {
  72. result = false;
  73. }
  74. }
  75.  
  76. return result;
  77. }
  78. void markChecked(int i, int j, vector<vector<char>> &board,
  79. vector<vector<bool>> &checked) {
  80. queue<Pos> q;
  81. bool result = true;
  82. q.push(Pos(i, j));
  83. while (!q.empty()) {
  84. Pos pos = q.front();
  85. q.pop();
  86. i = pos.row;
  87. j = pos.col;
  88. board[i][j] = 'X';
  89. checked[i][j] = false;
  90. if (j - 1 >= 0) {
  91. if (checked[i][j - 1]) {
  92. q.push(Pos(i, j - 1));
  93. checked[i][j - 1] = false;
  94. }
  95. }
  96. if (j + 1 < board[0].size()) {
  97. if (checked[i][j + 1]) {
  98. q.push(Pos(i, j + 1));
  99. checked[i][j + 1] = false;
  100. }
  101. }
  102. if (i + 1 < board.size()) {
  103. if (checked[i + 1][j]) {
  104. q.push(Pos(i + 1, j));
  105. checked[i + 1][j] = false;
  106. }
  107. }
  108. if (i - 1 >= 0) {
  109. if (checked[i - 1][j]) {
  110. q.push(Pos(i - 1, j));
  111. checked[i - 1][j] = false;
  112. }
  113. }
  114. }
  115. }
  116. typedef struct Pos {
  117. int row, col;
  118. Pos(int i, int j): row(i), col(j) {};
  119. };
  120. };

2/21/2013

Restore IP Addresses

Restore IP AddressesAug 8 '12
Given a string containing only digits, restore it by returning all possible valid IP address combinations.
For example:
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
This one is actually more tricky than it seems to be as it involves several corner cases.
DFS

  1. class Solution {
  2. public:
  3. vector<string> restoreIpAddresses(string s) {
  4. // Start typing your C/C++ solution below
  5. // DO NOT write int main() function
  6. if (s.size() > 12 || s.size() < 4) return vector<string>();
  7. return getValidIP(s.c_str(), 0);
  8. }
  9. vector<string> getValidIP(const char *c, int n) {
  10. const char *head = c;
  11. if (n == 3) {
  12. int num = 0;
  13. while (*c != '\0') {
  14. num = num * 10 + *c - '0';
  15. ++c;
  16. }
  17. vector<string> ret;
  18. // last segment requirements
  19. // at least one digit and at most one leading zero
  20. if (c - head > 1 && *head == '0' || c == head) return ret;
  21. // segment number cannot exceed 255
  22. if (num <= 255) {
  23. string seg(head, c - head);
  24. ret.push_back(seg);
  25. }
  26. return ret;
  27. }
  28. int num = 0;
  29. vector<string> ret;
  30. for (int i = 0; i < 3; ++i) {
  31. // reaches end or digits exceed 3
  32. if (*c == '\0' || c - head > 2) break;
  33. num = num * 10 + *c - '0';
  34. // each segment can be at most 255
  35. if (num > 255) break;
  36. vector<string> rest = getValidIP(++c, n + 1);
  37. string add_seg(head, c - head);
  38. for (auto s : rest) {
  39. string address(add_seg);
  40. address += ".";
  41. address += s;
  42. ret.push_back(address);
  43. }
  44. // only one leading 0 allowed
  45. if (*(c - 1) == '0' && i == 0) break;
  46. }
  47. return ret;
  48. }
  49. };

2/11/2013

Reverse Linked List II

Reverse Linked List IIJun 27 '12
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m  n ≤ length of list.
This looks fairly easy but actually it's pretty tricky. Each recursion takes the node to be processed and returns itself so that the upper level can change the 'next' pointer backwards as stack pops. The special case is that during the backward process, when m == 0 we reach the first node in the region to be reversed (let's call it 'region'). At that time the node before it should get the next node after the 'region'. That's where the nodeAfterN is used. Also the node before m == 0 should get the original last node in the 'region', which now becomes the head node in the 'region'. This is achieved by returning the pointer of that last node to the upper level of recursion, AKA nodeAtN.
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode *reverseBetween(ListNode *head, int m, int n) {
  12. // Start typing your C/C++ solution below
  13. // DO NOT write int main() function
  14. nodeAtN = NULL;
  15. nodeAfterN = NULL;
  16. return revHelper(head, m - 1, n - 1);
  17. }
  18. ListNode *revHelper(ListNode *current, int m, int n) {
  19. if (!current) return NULL;
  20. ListNode *ret = current;
  21. if (m > 0) {
  22. current->next = revHelper(current->next, m - 1, n - 1);
  23. }
  24. else if (n > 0) {
  25. ListNode *currentNext = revHelper(current->next, m - 1, n - 1);
  26. currentNext->next = current;
  27. if (m == 0) {
  28. current->next = nodeAfterN;
  29. ret = nodeAtN;
  30. }
  31. }
  32. else if (n == 0) {
  33. nodeAtN = current;
  34. nodeAfterN = current->next;
  35. }
  36. return ret;
  37. }
  38. private:
  39. ListNode *nodeAfterN;
  40. ListNode *nodeAtN;
  41. };