From 4d5dbca2406437ca9de615f2a2d794e4b9372ddf Mon Sep 17 00:00:00 2001 From: Vahagn Khachatryan Date: Tue, 24 Apr 2018 10:44:42 -0400 Subject: [PATCH] number_of_islands.cpp --- .../interviews/training/number_of_islands.cpp | 115 ++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 puzzles/interviews/training/number_of_islands.cpp diff --git a/puzzles/interviews/training/number_of_islands.cpp b/puzzles/interviews/training/number_of_islands.cpp new file mode 100644 index 0000000..95b1bd4 --- /dev/null +++ b/puzzles/interviews/training/number_of_islands.cpp @@ -0,0 +1,115 @@ +/* +VIM: let b:lcppflags="-std=c++14 -O2 -pthread" +VIM: let b:wcppflags="/O2 /EHsc /DWIN32" +VIM-: let b:argv="" +*/ +#include +#include +#include +#include +#include + +/* + FB On-site March + + Q: Find number of Islands. + XXXOO + OOOXX + XXOOX + Return 3 islands. + 1 1 1 O O + O O O 2 2 + 3 3 O O 2 +*/ +int number_of_islands( const std::vector& board ) +{ + auto n = board.size(); + auto m = board.front().size(); + std::unordered_map g; + + auto idx = [m](size_t i, size_t j){ + return i*m+j; + }; + + auto root = [&g](size_t idx){ + for (; g[idx] != idx; idx = g[idx] ); + return idx; + }; + + for (size_t i = 0; i < n; ++i ){ + for (size_t j = 0; j < m; ++j){ + if (board[i][j] == 'x'){ + if (j>0 && board[i][j-1] == 'x'){ + g[idx(i,j)]=g[idx(i,j-1)]; + if (i>0 && board[i-1][j] == 'x'){ + g[root(idx(i-1,j))]=g[idx(i,j)]; + } + } + else if (i>0 && board[i-1][j] == 'x'){ + g[idx(i,j)]=g[idx(i-1,j)]; + } + else { + g[idx(i,j)]=idx(i,j); + } + } + } + } + + int count = 0; + for ( const auto& node: g){ + if ( node.first == node.second ){ + ++count; + } + } + + return count; +} + +int main ( void ) +{try{ + + std::cout << number_of_islands({ + "xxxoo", + "oooxx", + "xxoox" + }) << std::endl; + + std::cout << number_of_islands({ + ".xx..", + "xx...", + "xxxxx" + }) << std::endl; + std::cout << number_of_islands({ + "....x", + "....x", + "xxxxx" + }) << std::endl; + std::cout << number_of_islands({ + "xxxxx", + "xxxxx", + "xxxxx" + }) << std::endl; + std::cout << number_of_islands({ + "xxxxx", + "....x", + "xxx.x", + "x...x", + "xxxxx" + }) << std::endl; + + + return 0; +} +catch ( const std::exception& e ) +{ + std::cerr << std::endl + << "std::exception(\"" << e.what() << "\")." << std::endl; + return 2; +} +catch ( ... ) +{ + std::cerr << std::endl + << "unknown exception." << std::endl; + return 1; +}} +