/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
struct Cell{
int row;
int col;
};
struct Direction{
int row_adder;
int col_adder;
};
bool Valid(Cell& cell, std::vector<std::vector<int>>& matrix) {
int total_rows = matrix.size();
int total_cols = matrix[0].size();
if (cell.row < 0) {
return false;
}
if (cell.row >= total_rows) {
return false;
}
if (cell.col < 0) {
return false;
}
if (cell.col >= total_cols) {
return false;
}
if (matrix[cell.row][cell.col] != -1) {
return false;
}
return true;
}
void ChangeDirection(Direction& direction) {
// if right then go down
if (direction.row_adder == 0 && direction.col_adder == 1) {
direction.row_adder = 1;
direction.col_adder = 0;
return;
}
// if down then go left
if (direction.row_adder == 1 && direction.col_adder == 0) {
direction.row_adder = 0;
direction.col_adder = -1;
return;
}
// if left then go up
if (direction.row_adder == 0 && direction.col_adder == -1) {
direction.row_adder = -1;
direction.col_adder = 0;
return;
}
// if up then go right
if (direction.row_adder == -1 && direction.col_adder == 0) {
direction.row_adder = 0;
direction.col_adder = 1;
return;
}
// continue
return;
}
bool Update(Cell& cell, Direction& direction, std::vector<std::vector<int>>& matrix) {
Cell next_cell = Cell{
.row = -1,
.col = -1
};
next_cell.row = cell.row + direction.row_adder;
next_cell.col = cell.col + direction.col_adder;
if (!Valid(next_cell, matrix)) {
// change direction and check
ChangeDirection(direction);
next_cell.row = cell.row + direction.row_adder;
next_cell.col = cell.col + direction.col_adder;
// the next cell is still not valid,
// this implies that we have no other cells to fill now.
if (!Valid(next_cell, matrix)) {
return false;
}
cell = next_cell;
return true;
}
// Otherwise the next cell is valid
cell = next_cell;
return true;
// construct a matrix of size (m x n) with values (-1).
std::vector<std::vector<int>> matrix;
for(int num_rows = 0; num_rows < m; num_rows++) {
std::vector<int> row(n, -1);
matrix.push_back(row);
}
// Next, is to update the directions
ListNode* iter = head;
Cell cell = Cell{
.row = 0,
.col = 0
};
Direction direction = Direction{
.row_adder = 0,
.col_adder = 1
};
while(iter != nullptr) {
// Fill the current cell with value
matrix[cell.row][cell.col] = iter->val;
// Update the cell
bool successfull_update = Update(cell, direction, matrix);
if (!successfull_update) {
break;
}
// otherwise continue;
iter = iter->next;
}
return matrix;
}
};